NSF API client
Architecture
The NSFApiClient class that owns every NSF Award API quirk: parameter preparation, response parsing, serviceNotification errors, retries, cancellation, and the cached multi-page fetch behind search_by_pi with includeCoPIs.
NSFApiClient in src/client/nsf-api-client.ts is the only code that talks to the NSF Award API. It owns every upstream quirk so that tools work with clean, normalized records: it normalizes dates, clamps page sizes, phrase-quotes some fields, turns HTTP-200 error notices into thrown errors, retries transient failures, and passes every record through normalizeAward.12
The module exports one shared instance, nsfApiClient = new NSFApiClient(configFromEnv()), which every tool handler and both resource templates use.13 Tests either spy on its methods or build their own NSFApiClient and mock its axios instance (see Testing).4
The upstream behaviour the client works around is documented in the NSF API section; this page describes the code. The parameters the client may send are typed as NSFSearchParams in src/types/nsf-api.types.ts, which lists only names verified against the live service, because the API rejects unknown names with AwardAPI-002.5
Constants
| Name | Value | Meaning |
|---|---|---|
NSF_API_BASE_URL |
https://www.research.gov/awardapi-service/v1 |
Default base URL |
NSF_MAX_PAGE_SIZE |
25 |
Largest page searchAwards requests |
NSF_RESULT_CAP |
10000 |
The API reports at most this many matches and serves no record past it |
PHRASE_FIELDS (internal) |
awardeeName, perfLocation, fundProgramName |
Fields whose multi-word values are wrapped in quotes |
DATE_FIELDS (internal) |
startDateStart, startDateEnd, expDateStart, expDateEnd, dateStart, dateEnd |
Fields normalized to mm/dd/yyyy |
NSF_RESULT_CAP is also used by buildSearchOutput (to compute hasMore and capped) and by pagingHint (to print 10000+), both in src/tools/shared.ts.6 The cap and page sizes are described from the API side in Paging and limits.
Configuration
The constructor takes an NSFApiClientConfig. configFromEnv() fills it from environment variables:1
| Option | Environment variable | Default | Meaning |
|---|---|---|---|
baseURL |
NSF_API_BASE_URL |
https://www.research.gov/awardapi-service/v1 |
API base URL; an empty value uses the default |
timeout |
NSF_API_TIMEOUT_MS |
15000 |
Per-attempt timeout in ms |
maxRetries |
NSF_API_MAX_RETRIES |
2 |
Retries after the first attempt |
retryDelay |
none | 1000 |
Base backoff delay in ms (constructor only) |
cacheTtlMs |
NSF_API_CACHE_TTL_MS |
300000 (5 minutes) |
How long searchAllPages results are cached; 0 disables the cache |
The numeric variables go through envNumber(), which ignores a value that is blank, not a finite number, or negative, so the default applies.1 All server settings are listed in Configuration.
The axios instance sends Accept: application/json and User-Agent: nsf-awards-mcp/<version>, where the version comes from package.json through src/version.ts. A request interceptor logs each request at debug level as NSF API request with its URL and parameters.17
Public methods
| Method | Endpoint | Returns |
|---|---|---|
searchAwards(params, { signal }) |
GET /awards.json |
One page of at most 25 records: { awards, totalResults, hasMore } |
searchAllPages(params, { signal, maxRecords }) |
GET /awards.json, usually twice |
Every record of a search, up to maxRecords (default 250) |
getAward(awardId, { signal }) |
GET /awards/{id}.json |
The normalized record, or null when the id matches nothing |
getProjectOutcomes(awardId, { signal }) |
GET /awards/{id}/projectoutcomes.json |
NSFProjectOutcome, or null when the award or its report is missing |
The award id is passed through encodeURIComponent in both lookup paths. The endpoints are described in Award search, Award by id and Project outcomes.1
getProjectOutcomes reads the record’s projectOutComesReport HTML. When the award or the report is missing it returns null. Otherwise it returns awardId, title, pdPIName, awardeeName (falling back to awardee), startDate, expDate, outcomesReport (the HTML converted by htmlToText, see Normalization) and outcomesReportHtml (the HTML as filed).1
Preparing parameters
Every search goes through the private prepareParams(params, maxPageSize), which runs these steps in order:1
- Drop empty values. String values are trimmed. A value that is
undefined,nullor''after trimming is left out of the query. - Normalize dates. Each
DATE_FIELDSvalue goes throughnormalizeToNSFDate(see Normalization), which returnsundefinedfor anything it cannot read as a real calendar date.8 A value that does not parse throwsInvalid date for <field>: <value> (expected mm/dd/yyyy or yyyy-mm-dd). Dropping the filter instead would return unfiltered results as if it had applied. - Clamp
rpp. Whenrppis set, it is truncated to an integer and clamped to[1, maxPageSize]. Then, ifoffset(default 0) is below 10000,rppis cut further to10000 - offset, because a page reaching past record 10000 fails upstream with AwardAPI-004. - Quote phrases. A
PHRASE_FIELDSvalue that contains whitespace has any"characters removed and is wrapped in double quotes. Unquoted, the API matches any of the words.
maxPageSize is 25 for searchAwards. It is maxRecords (250 by default) only for the remainder request inside searchAllPages.1 The tool input schemas already reject bad dates, reversed ranges and limit outside 1 to 25, so step 2 and the 25-record clamp are a second line of defence for tool calls.29
Reading responses
get(path, params, signal) performs the request, parses the body, checks it for service errors and checks that it is an NSF reply:1
parseResponse(data)accepts a body axios already parsed as JSON, a JSON string, or an XML string. XML goes throughxml2js.parseStringPromisewithexplicitArray: falseandignoreAttrs: true. A body of another type throwsUnexpected NSF API response format. A body that parses as neither JSON nor XML, or that parses tonullor a non-object (an empty body or a barenull), throwsFailed to parse NSF API response.assertNoServiceError(data)throws whenresponse.serviceNotificationholds any notice whosenotificationTypeisERRORorFATAL(case-insensitive). The message is each notice as<notificationCode>: <notificationMessage>, joined with;. The API reports rejected parameters (AwardAPI-002) this way with HTTP 200, and a request past record 10000 as aFATALAwardAPI-004 notice.12assertNSFResponse(data, contentType)throwsUnexpected NSF API response (no "response" object, content-type <type>)when the body has no top-levelresponseobject (or it is not an object). Every real reply has one, even a search with no matches, so an HTML error page,{}or a proxy’s JSON error fails instead of reading as “no results” or “award not found”. The content-type part comes from the reply’scontent-typeheader and is left out when there is none.extractAwards(data)returns[]whenresponse.awardis missing, treats a singleawardobject as a one-element list, and runsnormalizeAwardon each record (see Normalization).
For a search page, searchPage computes the paging fields from response.metadata.totalCount, which it converts with Number() because XML bodies carry numbers as strings:1
| Field | With a numeric totalCount |
Without one |
|---|---|---|
totalResults |
totalCount |
offset + awards.length |
hasMore |
offset + awards.length < min(totalCount, 10000) |
awards.length equals the prepared rpp (or the page-size limit when rpp is unset) |
For a single award, fetchSingle returns the first extracted record, or null when the list is empty: a missing award comes back as HTTP 200 with an empty award list. The tools turn null into a NotFoundError.12 An HTTP 404 does not map to null: since the API never answers a missing award that way, a 404 means it has moved or broken, so fetchSingle throws NSF API <operation> failed (HTTP 404) like any other error status.1
Retries
Retries use axios-retry on the client’s axios instance, with retries: maxRetries (default 2). The delay before retry n is retryDelay * 2^(n-1): 1000 ms, then 2000 ms with the defaults. Each retry is logged at debug level as Retrying NSF API request.1
A failed request is retried when it is:1
- a network error (
axiosRetry.isNetworkError), - a timeout (
ECONNABORTED), - HTTP
429, or - HTTP
500or above.
A cancelled request (axios.isCancel or ERR_CANCELED) is never retried. Other 4xx responses (404 included), HTTP-200 service notices and bodies without a response object are not retried.1
Cancellation
Tool handlers pass the MCP request’s AbortSignal (ctx.signal) to the client, which passes it to axios, so a client-side cancel aborts the HTTP request.12 The resulting error becomes NSF API <operation> was cancelled. searchAllPages handles signals differently, as described in the next section.
searchAllPages and its cache
search_by_pi with includeCoPIs: true runs a PI search and a Co-PI search and must merge, deduplicate and re-sort them before paging. The API’s offset cannot page that union, so the tool calls searchAllPages for both searches in parallel and pages the merged list itself (see search_by_pi). It is the only caller of searchAllPages.104
searchAllPages(params, { signal, maxRecords = 250 }) works like this:1
- It removes
offsetandrppfromparams; the remaining filters identify the search. - First page. It calls
searchAwardswithoffset: 0, rpp: 25to learn the total. - Refusal. If the total is above
maxRecords, it throwsSearch matches <total> awards, more than the <maxRecords> that can be merged; narrow it (e.g. add firstName, institution, stateCode or a date range). - Remainder. While the last page had more records, it requests
offset: <records so far>, rpp: <total - records so far>with a page-size limit ofmaxRecords. The API serves pages larger than 25 when asked (rpp=250returned 250 records when checked on 2026-12-04), so the remainder usually takes one request; the loop also copes with smaller pages.2 The loop stops when a page is empty,hasMoreis false, or the total is reached.
Results are cached in memory for cacheTtlMs:1
- Key.
JSON.stringify([filters, maxRecords]), wherefiltersexcludesoffsetandrpp. Paging through a merged result therefore reuses the same fetch. - Shared fetch. The cache stores the promise, not the result, so concurrent callers with the same key share one fetch. That fetch runs without any caller’s signal. Each caller waits through
withAbort(promise, signal), which rejects withNSF API search was cancelledwhen that caller’s signal aborts, and leaves the shared fetch running for the others. A fetch that every caller abandoned still completes and stays cached. - Failures. A rejected fetch is removed from the cache, so failures are never cached.
- Pruning. After each insert,
pruneCache()deletes expired entries and, while the cache holds more than 100 entries, deletes entries in insertion order (oldest first). - Disabled. With
cacheTtlMs <= 0, nothing is cached or shared and the fetch uses the caller’s signal directly.
Errors
toError(error, operation) turns axios errors into plain Errors with short messages. The operation is search, award lookup or project outcomes lookup:1
| Cause | Message |
|---|---|
| Request cancelled | NSF API <operation> was cancelled |
| HTTP error status (after retries for 429 and 5xx; at once for others, including 404) | NSF API <operation> failed (HTTP <status>) |
| Timeout without a response | NSF API <operation> failed (timed out) |
| Other network failure | NSF API <operation> failed (<axios message or "network error">) |
Failures other than cancellations are logged at error level as NSF API request failed with the operation, status and URL. Errors that are not axios errors, such as a service notice, a body without a response object, an invalid date or the searchAllPages refusal, pass through unchanged.1 The tool layer returns all of them as isError results; see Request flow and Errors.
-
src/client/nsf-api-client.ts ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 ↩12 ↩13 ↩14 ↩15 ↩16 ↩17 ↩18 ↩19 ↩20 ↩21 ↩22
-
CLAUDE.md, Architecture and Live API behaviour sections ↩ ↩2 ↩3 ↩4 ↩5 ↩6
-
src/server.ts (resource templates) ↩
-
NSF API types (RawNSFAward, NSFAward, NSFSearchParams) ↩
-
src/version.ts ↩
-
src/utils/date-utils.ts ↩
-
Tool input and output schemas ↩
-
src/tools/search-by-pi.ts ↩