By Rohan Muppa, ECE @ Purdue
A documented, read-only, programmatic client for D2L Brightspace. Scripts, cron jobs, and
other Node programs import it directly to read courses, grades, due dates, assignments,
announcements, syllabus, discussions, roster, and course content — no chat client in the way.
It shares its configuration and saved sign-in session with
brightspace-mcp-server (see
Relationship to brightspace-mcp-server), so a user
who has already run that project's setup wizard can start scripting immediately.
Connects to D2L Brightspace. Automatic login supports Purdue's Microsoft Entra flow, SUNY campus selection, and TU Delft NetID via SURFconext. Other schools need a compatible automated sign-in flow; unsupported login pages return an actionable error.
You need: Node.js 20+ and an available native credential store:
macOS Keychain, Windows Credential Manager, or Linux Secret Service. Linux requires
secret-tool and an unlocked desktop keyring (install libsecret-tools on Debian/Ubuntu).
npm install brightspace-apiRun the setup wizard once, from a terminal, to save your school URL and credentials:
npx brightspace-setup # after npm install
npx -y brightspace-api@latest setup # without installing firstPurdue students can add --purdue to skip entering the school URL; SUNY campuses can add
--suny; TU Delft students can add --tudelft (use your NetID, not your student email
address); Memorial University of Newfoundland students can add --mun. If you already run
brightspace-mcp-server on this machine, you can skip this step —
the two packages read the same ~/.brightspace-mcp/config.json and the same session under
~/.d2l-session/.
import { createBrightspaceClient, BrightspaceAuthExpiredError } from "brightspace-api";
const client = await createBrightspaceClient();
try {
const dueDates = await client.getUpcomingDueDates({ daysAhead: 7 });
if (dueDates.length === 0) {
console.log("Nothing due in the next 7 days.");
} else {
for (const item of dueDates) {
const due = new Date(item.dueDate).toLocaleString();
console.log(`${due} [${item.type}] ${item.title} (${item.courseName ?? item.courseId})`);
}
}
} catch (error) {
if (error instanceof BrightspaceAuthExpiredError) {
console.error(error.message); // tells the operator to run `brightspace-auth`
process.exitCode = 1;
} else {
throw error;
}
}By default (onAuthExpired: "fail", which is what createBrightspaceClient() uses with no
options), a call that needs a session which has expired and cannot be silently renewed over
HTTPS throws BrightspaceAuthExpiredError immediately — no browser is opened, nothing hangs.
This is the mode a scheduled job should use: a cron job cannot answer a phone.
import { createBrightspaceClient, BrightspaceAuthExpiredError } from "brightspace-api";
const client = await createBrightspaceClient(); // onAuthExpired: "fail" is the default
try {
const courses = await client.getMyCourses();
console.log(JSON.stringify(courses));
} catch (error) {
if (error instanceof BrightspaceAuthExpiredError) {
// error.message already tells the operator which command re-authenticates
// (npx brightspace-auth) — print it and let the next scheduled run retry.
console.error(error.message);
process.exit(1);
}
throw error;
}A process that is allowed to open a browser (an interactive script, not a cron job) can pass
onAuthExpired: "login" instead. The call then throws BrightspaceMfaPendingError as soon as
an MFA challenge appears — the sign-in keeps running in the background. Retry straight away: a
retry joins that sign-in and waits up to 45 seconds for you to approve it on your phone, returning
the result as soon as it completes (and throwing BrightspaceMfaPendingError again if it is still
unapproved by then):
import { createBrightspaceClient, BrightspaceMfaPendingError } from "brightspace-api";
const client = await createBrightspaceClient({
onAuthExpired: "login",
onMfaChallenge: (numberMatch) => {
console.log(numberMatch ? `Enter ${numberMatch} in Microsoft Authenticator` : "Approve the push notification");
},
});
async function getCoursesRetrying() {
try {
return await client.getMyCourses();
} catch (error) {
if (error instanceof BrightspaceMfaPendingError) {
console.log(error.message);
return getCoursesRetrying(); // waits for the approval; no sleep needed
}
throw error;
}
}A background sign-in nobody is waiting on is stopped 45 seconds after the last call that polled it
(or relayed its number from another process) was answered, without starting the MFA cooldown, so
the next call starts a fresh sign-in with a fresh number. Several processes can share one session
directory; a call whose sign-in finds another process's sign-in already holding the lock throws
BrightspaceMfaPendingError with that sign-in's number instead of a bare "already in progress".
While MFA is pending, make one Brightspace call at a time: a caller that holds parallel results
until the whole batch finishes can keep the number from the user until it is too late.
Three executables ship in node_modules/.bin: brightspace (the read-only JSON CLI, described
below), brightspace-auth (interactive re-authentication), and brightspace-setup (first-time
configuration). Each subcommand below maps 1:1 to a BrightspaceClient method, prints the
method's JSON result to stdout, and exits 0.
| Command | Maps to |
|---|---|
brightspace courses [--all] |
getMyCourses({ activeOnly: !all }) |
brightspace due [--days N] [--course ID] |
getUpcomingDueDates |
brightspace grades [--course ID] |
getMyGrades |
brightspace assignments [--course ID] |
getAssignments |
brightspace announcements [--course ID] [--count N] [--since ISO] |
getAnnouncements |
brightspace announcement-files --course ID --news ID [--file ID] [--max-chars N] |
getAnnouncementFiles |
brightspace assignment-files --course ID --folder ID [--file ID] [--max-chars N] |
getAssignmentFiles |
brightspace content --course ID [--type T] [--module TITLE] [--depth N] [--since ISO] |
getCourseContent |
brightspace syllabus --course ID |
getSyllabus |
brightspace discussions --course ID [--forum ID] [--topic ID] |
getDiscussions |
brightspace roster --course ID [--limit N] |
getRoster |
brightspace emails --course ID |
getClasslistEmails |
brightspace download --course ID (--topic ID | --course-path PATH | --folder ID --file ID | --news ID --file ID) --dir PATH [--name NAME] |
downloadFile |
brightspace transcript --course ID --topic ID (or --url URL) |
getVideoTranscript |
brightspace info |
getInfo |
brightspace auth |
sign in once (opens the MFA flow); same as brightspace-auth |
brightspace auth --logout |
end this computer's saved session early; same as brightspace-auth --logout |
brightspace setup |
save school and credentials; same as brightspace-setup |
brightspace --help / <command> --help |
usage |
To sign out early (on a shared computer, say), run npx -y brightspace-api@latest auth --logout.
It deletes this computer's saved Brightspace session, so the next request does a full sign-in.
Your saved password, authenticator enrollment, and config.json are kept. It only clears this
computer; it does not sign you out of Microsoft or Brightspace anywhere else. Another script or
process already running against this session (including a sibling brightspace-mcp-server)
notices on its next request and signs in again from scratch; one started before this update may
keep answering for up to an hour (the token lifetime) — restart it to drop that right away. If a
sign-in is in progress, it refuses and deletes nothing.
Errors go to stderr as {"error":{"code":…,"message":…}}, and stdout carries only the
JSON result — safe to pipe into jq:
brightspace due --days 3 | jq -r '.[] | "\(.dueDate)\t\(.title)"'If some courses' due dates could not be read, brightspace due still prints the array on stdout
and exits 0, and adds one line to stderr: {"failedCourses":[…]} naming those courses.
brightspace announcements without --since does the same with {"unreadCourses":[…],"notice":"…"}
for courses whose announcements could not be read.
Likewise, when Brightspace hides some people's email, brightspace emails prints the visible ones
on stdout and adds {"hiddenCount":N,"notice":"…"} to stderr.
Exit codes: 2 for BRIGHTSPACE_AUTH_EXPIRED, 3 for BRIGHTSPACE_MFA_PENDING, 4 for
BRIGHTSPACE_INVALID_ARGUMENT, 1 for anything else. Add --login to any command to switch
to onAuthExpired: "login" and print the MFA number to stderr as it arrives.
The CLI (
src/cli.ts) was still landing on a separate branch as this document was written. Re-check the flags above againstsrc/cli.tsonce it merges — this table is transcribed fromdocs/CONTRACT.md§6, not from the executable.
All methods live on the object createBrightspaceClient() resolves to. Every method throws a
BrightspaceError subclass (see Errors) instead of returning one.
| Method | Args | Result |
|---|---|---|
getMyCourses(args?) |
GetMyCoursesArgs — activeOnly?: boolean |
Course[] |
getUpcomingDueDates(args?) |
GetUpcomingDueDatesArgs — daysAhead?: number (default 7), courseId?: number |
UpcomingDueDates (UpcomingItem[] with an optional failedCourses) |
getMyGrades(args?) |
GetMyGradesArgs — courseId?: number |
CourseGrades[] |
getAssignments(args?) |
GetAssignmentsArgs — courseId?: number |
AssignmentsResult |
getAssignmentFiles(args) |
GetAssignmentFilesArgs — courseId, folderId?, fileId?, extractText? (default true), maxChars? (default 12000) |
AssignmentFilesResult |
downloadFile(args) |
DownloadFileArgs — courseId, topicId? | coursePath? | folderId?/fileId? | newsId?/fileId?, downloadPath, customFilename? |
DownloadResult |
getAnnouncements(args?) |
GetAnnouncementsArgs — courseId?: number, count? (default 10), modifiedSince?: string |
AnnouncementsList | AnnouncementsFiltered (optional unreadCourses, notice) |
getAnnouncementFiles(args) |
GetAnnouncementFilesArgs — courseId, newsId?, fileId?, extractText? (default true), maxChars? (default 12000) |
AnnouncementFilesResult |
getCourseContent(args) |
GetCourseContentArgs — courseId, typeFilter? (default "all"), moduleTitle?, maxDepth?, modifiedSince? |
CourseContentResult (optional notice, progressUnavailable) |
getSyllabus(args) |
GetSyllabusArgs — courseId, downloadPath? |
SyllabusResult (optional attachmentUnreadable, notice, externalSyllabusSources, externalSyllabusNote, externalSyllabusDiscovery) |
getDiscussions(args) |
GetDiscussionsArgs — courseId, forumId?, topicId? |
DiscussionsResult |
getRoster(args) |
GetRosterArgs — courseId, includeStudents? (default false), searchTerm?, limit? (default 100) |
RosterResult (optional unavailable, notice) |
getClasslistEmails(args) |
GetClasslistEmailsArgs — courseId |
ClasslistEmailsResult (ClasslistEmailEntry[] with optional hiddenCount, notice) |
getVideoTranscript(args) |
GetVideoTranscriptArgs — courseId?, topicId?, videoUrl?, offset? (default 0), maxChars? (default 12000) |
VideoTranscriptResult |
getInfo() |
— | ClientInfo |
In the all-courses form of getMyGrades (no courseId), a course whose grades could not be
read (a 404, a 5xx, a network error) stays in the array with grades: [] and a failed field —
{ code, status?, gradeUrl, notice } — so an empty list there means "unknown", not "no grades".
failed is absent on every course that was read. A course answering 403 is still left out, and a
sign-in problem still throws.
getUpcomingDueDates still resolves to an array of UpcomingItems. When a course's assignments,
quizzes, or discussions could not be read (a 404, a 5xx, a network error), its missing items are
reported in a failedCourses property on that array — each { courseId, courseName, sources, code, status?, notice } — so a course listed there means "unknown", not "nothing due". This
applies with courseId too: an empty array with failedCourses set is a failed read, not an
empty course. failedCourses is absent when every course was read. A 403 is still skipped
quietly, and a sign-in problem throws, as in getAssignments. Array methods such as filter and
JSON.stringify do not carry the property along, so read it from the value the call returned.
getAssignments marks reads that failed instead of showing them empty. A dropbox assignment whose
feedback could not be read (a 403, a 5xx, a network error; a 404 just means no feedback yet) has a
feedbackUnavailable field — { code, status?, notice } — so its feedback: null means
"unknown", not "not graded". A course whose quiz list could not be read (anything but a 404) has
a quizzesUnavailable field of the same shape, on the single-course result or on its entry in
courses: its quizzes are then only those found through the course content, and others may be
missing. Both fields are absent when the read succeeded.
getAnnouncements without courseId reads each course's announcements separately. A course
whose announcements could not be read (a 403, a 5xx, a network error) is left out of the list but
named in unreadCourses — each { courseId, courseName, status?, code } — with a notice
naming those courses, so a course missing from the list means "unknown", not "no announcements".
Without modifiedSince the result is still an array (AnnouncementsList) and both are properties
on it, like failedCourses, which JSON.stringify drops; the CLI writes them to stderr as one
JSON line ({"unreadCourses":[…],"notice":"…"}). With modifiedSince they are fields of the
AnnouncementsFiltered object. Both are absent when every course was read. Unlike
getAssignments, a 403 is named too, since "anything new?" cannot be answered for that course. A
sign-in problem throws.
getRoster without includeStudents reads the instructors and the TAs on separate routes. When
one of them could not be read (a 404, a 5xx, a network error), the result lists whoever was read
plus an unavailable field naming the missing roles ("instructors", "TAs") and a notice
saying they may be missing, so a roster with no TAs there means "unknown", not "no TAs". Both are
absent when every role was read. A 403 is still skipped quietly, and a sign-in problem throws, as
in getAssignments.
getCourseContent reads each module's items from its own /structure/ route, falling back to the
items the parent listing embedded. When neither could be read (a 403, a 404, a 5xx, a network
error, an answer that is not a list), the module stays in the tree, under any typeFilter or
modifiedSince, with children: null and a childrenUnavailable field — { status, reason },
status null when Brightspace gave none — and the result carries a notice saying how many
modules could not be read and that they must not be reported as empty. children: [] still means
the module was read and is empty. childrenUnavailable and notice are absent when every module
was read. A sign-in problem throws, as in getAssignments.
Each topic's isCompleted is true or false from the user's content progress, or null when
that progress could not be read (a 5xx, a timeout, a network error); the result then carries a
progressUnavailable note saying completion is unknown and topics must not be reported as not
completed. A 403 or 404 on the progress route still means the course has no progress for the user:
isCompleted stays false and there is no note. A sign-in problem on the progress route throws.
getClasslistEmails still resolves to an array of ClasslistEmailEntrys, leaving out people
whose email Brightspace hides. When anyone was left out, the array carries a hiddenCount
property (how many) and a notice saying how many of the course's people are not listed and why,
so a short or empty list there means "some emails are hidden", not "that is the whole class".
Both are absent when every email was visible. Like failedCourses, they are properties on the
array that JSON.stringify drops; the CLI writes them to stderr as one JSON line.
getSyllabus reads the overview's attachment from /overview/attachment. A 404 there means the
course has no attachment (hasAttachment: false). Any other failure (a 403, a 5xx, a timeout, a
network error) sets attachmentUnreadable: true and a notice saying an attachment may exist but
could not be read, so hasAttachment: false then means "unknown", not "no syllabus file". With
downloadPath, that case throws BrightspaceForbiddenError (403), BrightspaceApiError (other
HTTP statuses) or BrightspaceNetworkError saying the attachment could not be read and nothing
was saved, instead of the BrightspaceNotFoundError a real 404 still gives. Both fields are absent
when the attachment was read or is known missing. A sign-in problem throws, as in
getAssignments.
getSyllabus also looks for a syllabus tool (e.g. Simple Syllabus) the course links through LTI:
its LTI 1.1 links, its LTI Advantage (1.3) links, and LTI launches in its content. Matches are
listed in externalSyllabusSources ({ title, location, url }, query string or session
parameters removed); their contents cannot be read. externalSyllabusDiscovery
({ complete: false, unavailable, notChecked?, note }) is set whenever that search is not proof of
anything: a lookup that was refused or failed is named in unavailable, and when nothing was found
notChecked: ["course-navbar"] says the course navbar was never checked, since Brightspace has no
API for its links. So an empty externalSyllabusSources never means "this course has no
syllabus".
getDiscussions with only courseId lists every forum with its topics; with forumId it
lists that forum's topics with their posts. When one forum's topics, or one topic's posts,
could not be read (a 403, a 404, a 5xx, a network error), that forum or topic is still listed
with an empty topics / posts (and postCount: 0) plus a topicsUnavailable /
postsUnavailable field — { code, status?, notice } — so an empty list there means
"unknown", not "empty". The field is absent on every forum and topic that was read. A sign-in
problem throws, as in getAssignments.
Every argument and result type is exported from brightspace-api's root entry point. The
api property on the returned client (client.api, type D2LApiClient) is an escape hatch
for making raw, authenticated D2L API calls the facade doesn't cover — it is not part of the
stable contract in the same way the 15 methods above are.
Every error the client or CLI throws is a BrightspaceError subclass with a stable code.
Scripts should branch on code; people should read message.
| Code | Class | When |
|---|---|---|
BRIGHTSPACE_AUTH_EXPIRED |
BrightspaceAuthExpiredError |
The saved session is gone and the call was not allowed to open a browser (onAuthExpired: "fail", the default). |
BRIGHTSPACE_MFA_PENDING |
BrightspaceMfaPendingError |
With onAuthExpired: "login", a browser sign-in is waiting on an MFA approval or number match. numberMatch carries the digits when the tenant shows one. |
BRIGHTSPACE_AUTH_FAILED |
BrightspaceAuthFailedError |
A browser sign-in ran and did not produce a session. kind says why (busy, cooldown, unsupported, secureStorage, transport, timeout, failed, inProgress). inProgress means a sign-in is still starting after the 55-second per-call budget; it keeps running, and a retry joins it. |
BRIGHTSPACE_NOT_FOUND |
BrightspaceNotFoundError |
The course or item doesn't exist, you don't have access, or (for getVideoTranscript) no transcript is available. |
BRIGHTSPACE_FORBIDDEN |
BrightspaceForbiddenError |
Brightspace returned HTTP 403 for the request. |
BRIGHTSPACE_RATE_LIMITED |
BrightspaceRateLimitedError |
Brightspace rate-limited the request. |
BRIGHTSPACE_NETWORK |
BrightspaceNetworkError |
The connection to Brightspace (or, for transcripts, the video platform) failed, or a token could not be silently renewed. |
BRIGHTSPACE_INVALID_ARGUMENT |
BrightspaceInvalidArgumentError |
Arguments failed schema validation. issues is an array of "path: message" strings. |
BRIGHTSPACE_DOWNLOAD_FAILED |
BrightspaceDownloadError |
downloadFile or getSyllabus refused to save a file. kind says why (unsupportedType, undetectableType, badFilename, pathTraversal, tooLarge). |
BRIGHTSPACE_API_ERROR |
BrightspaceApiError |
Brightspace returned some other non-2xx status. status carries the HTTP code. |
BRIGHTSPACE_UNEXPECTED |
BrightspaceError |
Anything else. |
toPublicError, exported from brightspace-api/errors, is the function that performs this
mapping; you should not normally need to call it yourself.
The client reads the same configuration as brightspace-mcp-server, resolved in this order
(environment variable, then ~/.brightspace-mcp/config.json, then a built-in default):
| Setting | Env override | Config key | Default |
|---|---|---|---|
| School URL | D2L_BASE_URL |
baseUrl |
https://purdue.brightspace.com |
| Username | D2L_USERNAME |
username |
— |
| Session directory | D2L_SESSION_DIR |
sessionDir |
~/.d2l-session |
| Headless sign-in | D2L_HEADLESS |
headless |
true |
| Passwordless sign-in (Microsoft Entra only) | D2L_PASSWORDLESS |
passwordless |
false |
| Remember this device for MFA (Microsoft Entra only) | D2L_REMEMBER_MFA |
rememberMfa |
false |
| Token TTL (seconds) | D2L_TOKEN_TTL |
tokenTtl |
3600 |
| Only active courses | D2L_ACTIVE_ONLY |
activeOnly |
true |
| Include only these course IDs | D2L_INCLUDE_COURSES (comma-separated) |
includeCourses |
— |
| Exclude these course IDs | D2L_EXCLUDE_COURSES (comma-separated) |
excludeCourses |
— |
| Campus (SUNY) | D2L_CAMPUS |
campus |
— |
The saved password lives in the OS credential store (macOS Keychain, Windows Credential
Manager, Linux Secret Service), never in config.json or an environment variable. A script
can also skip config-file/env resolution entirely by passing a fully-built AppConfig as
createBrightspaceClient({ config }) — there is no password option; credentials never enter
through the client's options.
setup no longer asks about passwordless sign-in and always saves a password; turn it on by
setting D2L_PASSWORDLESS=true (or hand-editing passwordless into config.json). With it on,
no password is read or saved at all: the default Entra flow submits only the username and waits
for your phone's approval, so every sign-in — including an automatic one after a session expires
— needs that approval. This suits interactive use, not unattended or scheduled jobs, and only
applies to Microsoft Entra schools; passwordless phone sign-in must already be registered in
Microsoft Authenticator, or sign-in fails at once naming D2L_PASSWORDLESS instead of waiting
out the usual timeout.
Automatic sign-in supports Purdue's Microsoft Entra flow, the shared SUNY Brightspace site
(with campus selection), and TU Delft NetID sign-in via SURFconext. Other D2L schools can
still be used — point baseUrl at your school's Brightspace URL — but an unsupported login
page returns an actionable BrightspaceAuthFailedError (kind: "unsupported") rather than
hanging.
- Read-only. No method or CLI command submits, posts, grades, or modifies anything in Brightspace.
- No password option. Credentials are never accepted through
createBrightspaceClient(); they are only ever read from the native OS credential store, written there bybrightspace-setup. - Nothing secret in errors or logs.
toPublicErroronly ever produces text this package writes itself, from a closed set ofkind/status values — never a token, cookie, raw Brightspace response body, or child-process output.log()writes to stderr only; nothing is ever written to stdout except a method's JSON result.
brightspace-api is the data layer: a typed, read-only client extracted from
brightspace-mcp-server 3.6.1 so it
can be used outside of an MCP client. brightspace-mcp-server is the chat-client wrapper — it
depends on the Model Context Protocol SDK and exposes these same operations as MCP tools to
Claude Desktop, Claude Code, Cursor, and similar assistants. The two packages share
configuration (~/.brightspace-mcp/config.json) and saved session state (~/.d2l-session/),
so setting up one lets the other run without a second sign-in.
MIT — see LICENSE. Copyright (c) 2026 Rohan Muppa.