Testing
Guide
How nsf-awards-mcp is tested: the offline Jest suite, the live suite and smoke check against the real NSF API, fixtures, the verify skill and the CI workflows.
The project has three layers of tests. The offline suite (npm test) runs Jest against mocked
NSF API responses built from real fixtures and never touches the network. The live suite
(npm run test:live) runs the API client and the built server against the real NSF Award API. The
live smoke check (npm run validate:live) makes one call per tool through the built server in a
few seconds.1
CI runs the offline suite on pushes and pull requests (see CI workflows). A separate workflow runs the live suite weekly and on demand, to catch upstream API drift.2 Live tests never assert exact counts, because NSF data changes.3
Commands
npm test # offline suite; tests/live is excluded
npx jest tests/tools/search-by-pi.test.ts # one file
npx jest -t "includeCoPIs" # tests whose name matches
npm test -- --coverage # coverage report in coverage/
npm run test:watch # watch mode
npm run test:live # build, then NSF_LIVE=1 against the real API (slow, serial)
npm run validate:live # build, then a fast live smoke check over stdio
These commands come from package.json, CLAUDE.md and the developer guide.3
Offline suite
Jest configuration
jest.config.cjs configures the offline suite:4
| Setting | Value |
|---|---|
preset |
ts-jest |
testEnvironment |
node |
roots |
<rootDir>/tests |
testMatch |
**/*.test.ts |
testPathIgnorePatterns |
/node_modules/, <rootDir>/tests/live/ |
collectCoverageFrom |
src/**/*.ts, excluding src/**/*.d.ts and src/types/** |
coverageDirectory |
coverage |
coverageReporters |
text, lcov, html |
setupFilesAfterEnv |
<rootDir>/tests/setup.ts |
testTimeout |
30000 ms |
Jest runs the TypeScript sources as CommonJS through ts-jest, with module: commonjs,
moduleResolution: node, isolatedModules, allowSyntheticDefaultImports and
esModuleInterop.4 Two moduleNameMapper entries bridge the gap to the ESM sources:
- Any relative import of
versionorversion.jsmaps totests/support/version.ts. The realsrc/version.tsusesimport.meta, which CommonJS Jest cannot load. The stand-in reads the samepackage.json, so tests see the real name and version. - Any other relative import ending in
.jshas the extension stripped, so./shared.jsresolves to./shared.ts.
If Jest fails on import.meta, something imports src/version.ts through a path that the mapper
does not match. Import it as ./version.js or ../version.js.5
The setup file
tests/setup.ts runs before every test file. It sets NODE_ENV=test and LOG_LEVEL=error, and it
replaces the winston logger with jest.fn() stubs for info, error, warn, debug and
verbose.6
Unless NSF_LIVE=1, it also points the shared client at a closed local port, so that an unmocked
request fails fast instead of reaching the real API:6
| Variable | Offline value |
|---|---|
NSF_API_BASE_URL |
http://127.0.0.1:9/awardapi-service/v1 |
NSF_API_MAX_RETRIES |
0 |
NSF_API_TIMEOUT_MS |
2000 |
These are the same variables the server reads at run time; see Configuration.
Layout
| Directory | Files | What they cover |
|---|---|---|
tests/client/ |
nsf-api-client.test.ts |
NSFApiClient: searchAwards (totals and hasMore, parameter preparation, service notifications, transport failures, bodies without a response object), getAward and getProjectOutcomes (including a 404 as an error, not “not found”), searchAllPages and its cache, assertNoServiceError, parseResponse, configFromEnv. |
tests/tools/ |
search-awards.test.ts, search-by-institution.test.ts, search-by-pi.test.ts, get-award-details.test.ts, get-project-outcomes.test.ts, shared.test.ts, schemas.test.ts |
Each tool handler and its argument mapping, the shared helpers (NotFoundError, statusParams, shapeAward, buildSearchOutput and the 10,000 record cap), and the input and output schemas (defaults, paging bounds, dates, ranges, keyword syntax, required names, award ids, removed and unknown fields). |
tests/server/ |
server.test.ts, http.test.ts |
pagingHint, toCallToolResult, and the MCP protocol on both eras (handshake, tools/list, tool calls, output schema enforcement, invalid input, client errors, resources). The HTTP app: routes, Host and Origin validation, real clients on both eras, httpOptionsFromEnv. |
tests/utils/ |
date-utils.test.ts, html-utils.test.ts, normalize.test.ts |
Date parsing and formatting (including time-zone independence), htmlToText, and record normalization. |
tests/live/ |
api.live.test.ts, mcp.live.test.ts |
The live suite (below). Excluded from npm test. |
tests/support/ |
version.ts |
Jest stand-in for src/version.ts. |
tests/fixtures/ |
JSON and XML responses | Real, trimmed API responses (below). |
The file and test-group names above come from the test sources.7
Fixtures
tests/fixtures/ holds real, trimmed NSF API responses.5
| File | Contents |
|---|---|
award-1114898.json |
Award 1114898, which has a Project Outcomes Report and Co-PIs. |
award-9307607-no-report.json |
Award 9307607, which has no outcomes report. |
award-former-copi.json |
Award 2535322, a record with a former Co-PI. |
award-missing.json |
The response for a missing award id: an empty award list and totalCount 0. |
invalid-parameter.json |
An HTTP-200 serviceNotification with AwardAPI-002 for an invalid parameter (awardeeOrganization). |
search-wildfire-page.json |
A 3-award keyword=wildfire search page (rpp 3, totalCount 981 when captured). |
search-page.xml |
An XML search page. |
The award ids, counts and notification code are read from the fixture files.7
Conventions
Build test data from fixtures. Run raw fixture records through normalizeAward, for example
normalizeAward(fixture.response.award[0]), so mocks carry real shapes. Do not hand-write numeric
amounts: the live API sends strings, and hand-written numbers once hid a string-concatenation
bug.5
Mock at the client boundary. For tool and server tests, spy on the shared client:
jest.spyOn(nsfApiClient, ...) with searchAwards, searchAllPages, getAward or
getProjectOutcomes. Do not automock the client module, because that also mocks constants such as
NSF_RESULT_CAP.5
Mock HTTP for client tests with axios-mock-adapter on the client’s private axios
instance:5
import MockAdapter from 'axios-mock-adapter';
import type { AxiosInstance } from 'axios';
import { NSFApiClient } from '../../src/client/nsf-api-client';
const client = new NSFApiClient({ maxRetries: 0, cacheTtlMs: 0 });
const mock = new MockAdapter((client as unknown as { client: AxiosInstance }).client);
mock.onGet('/awards.json').reply(200, fixture);
Parse before calling a handler. Handlers expect input the SDK has already validated, with
defaults applied, so call Schema.parse(input) first or pass a complete object.5
Drive the real server in process. tests/server/server.test.ts runs every protocol test on both
protocol eras:3
- Legacy (2025-11-25):
InMemoryTransport.createLinkedPair(), thenserver.connecton one end and a plainClienton the other. - Modern (2026-07-28):
serveStdio(() => createServer(), { transport })on one end and aClientpinned withversionNegotiation: { mode: { pin: '2026-07-28' } }on the other.
tests/server/http.test.ts starts createHttpApp() on an ephemeral port on 127.0.0.1. It sends
raw requests with node:http because fetch will not send a custom Host header, and connects
real clients with StreamableHTTPClientTransport.7 For what these transports do, see
Transports.
Live suite
npm run test:live builds the server, then runs Jest with NSF_LIVE=1, jest.live.config.cjs and
--runInBand.1 The live config extends the offline one with these
changes:8
| Setting | Value |
|---|---|
roots |
<rootDir>/tests/live |
testPathIgnorePatterns |
/node_modules/ only |
testTimeout |
120000 ms |
maxWorkers |
1 (one request stream at a time, to be polite to the public API) |
Every live suite is skipped unless NSF_LIVE=1 (the files fall back to describe.skip), and the
offline config ignores tests/live/ entirely, so only npm run test:live runs
them.8
tests/live/api.live.test.ts tests NSFApiClient against the real API with a 60-second timeout,
2 retries and the cache off. It takes the keyword=wildfire total as a baseline, then checks
paging (consecutive pages, the last page, the 10,000 cap, the last record under the cap, rpp
clamping, active plus expired partitioning), every search filter, the record shape, the detail and
outcomes endpoints, and errors (an AwardAPI-002 rejection and an invalid date). It also pins the API behaviour
that the tools rely on: piLastName is a prefix match while pdPIName matches whole words, and a keyword with two
quoted phrases matches almost nothing.7
tests/live/mcp.live.test.ts drives the built build/index.js with the MCP client SDK. It runs
the full tool contract over stdio on the legacy and the modern (2026-07-28) era, then starts the
server with MCP_TRANSPORT=http on a free port and repeats checks over Streamable HTTP. Among other things it checks
that the paging hint is also in the result’s hint field, that detail: "full" records leave out the outcomes
report and publications, that a keyword with two quoted phrases is rejected before any API call, and that a
search_by_pi full-name search returns no PI whose surname only starts with the last name. It fails
early with run npm run build first if build/index.js is missing.7
Live assertions follow three rules:3
- Use discriminating assertions: a filtered total must be below the
keyword=wildfirebaseline, and every returned record must satisfy the filter. - Never assert exact counts, because the data changes.
- Use the known fixture awards: 2632685 (full field set), 1114898 (has an outcomes report) and 9307607 (no report).
Live smoke check
npm run validate:live builds, then runs scripts/validate-live.mjs.1 The script
spawns build/index.js over stdio with LOG_LEVEL=error (unless LOG_LEVEL is set) and
checks:9
- A handshake on the legacy era and on the modern era (
2026-07-28). - That
tools/liston each era returns exactly the five tools (get_award_details,get_project_outcomes,search_by_institution,search_by_pi,search_nsf_awards), each with an object output schema. - One live call per tool on the modern era, checked through
structuredContent:
| Tool | Arguments | Check |
|---|---|---|
search_nsf_awards |
keyword: "wildfire", limit: 3 |
3 records returned, each with an id and no abstractText (summaries). |
search_by_institution |
institutionName: "University of Arizona", limit: 3 |
At least one record, and every awardeeName is exactly University of Arizona. |
search_by_pi |
a first and last name, limit: 5 |
At least one record, and every pdPIName contains both names. |
get_award_details |
awardId: "2632685" |
award.id is 2632685 and abstractText is a string. |
get_project_outcomes |
awardId: "1114898" |
awardId is 1114898 and outcomesReport is longer than 200 characters. |
Each check prints a line that starts with ok or FAIL. The run ends with All checks passed or
N failure(s) and exits with status 1 on any failure.9
The verify skill
.claude/skills/verify/SKILL.md is a Claude Code skill for end-to-end checks of the built server
with a real MCP client, over stdio and Streamable HTTP, against the live API.10 It
starts from npm run build, npm run test:live and npm run validate:live, then gives ad hoc
client scripts for both eras, HTTP checks, and a list of gotchas. Some of them:
/healthanswers with the status and thepackage.jsonversion, an unknown path returns 404, and a POST to/mcpwith a foreignHostheader returns 403.- Stop a background HTTP server by its PID.
pkill -f "node build/index.js"would also kill a stdio server that a client such as this repository’s.mcp.jsonstarted. totalCountis capped at 10000, so add akeyword(for examplewildfire) before judging whether a filter narrows a search.- Records are normalized: amounts are numbers and
activeAwdis a boolean, while the raw API sends strings. - Summaries carry only the summary fields. Ask for
detail: 'full'orprintFieldsto check a filter on another field.
Comparing with the raw API
When a live test fails but the unit tests pass, compare with the raw API to tell a server bug from an upstream change:5
curl -s -G https://www.research.gov/awardapi-service/v1/awards.json --data-urlencode keyword=wildfire --data-urlencode rpp=1
scripts/probe-nsf-api.sh [outdir] probes every endpoint and parameter the client uses with raw
curl requests. It prints the HTTP status, total count and first award id per request and saves each
response under outdir (default live-probe/, which is git-ignored).11 An ignored
parameter shows up as the same total as the unfiltered baseline. Check any new API parameter this way
before relying on it; see Search parameters.
CI workflows
CI/CD pipeline (ci.yml)
Runs on pushes to main, develop and claude/**, on v* tags, and on pull requests to main and
develop.12
| Job | Needs | Steps |
|---|---|---|
quality (Code Quality & Testing) |
Node 22, npm ci, npm run type-check, npm run lint, npm run format:check, npm test, npm run build, then upload build/ as an artifact kept for 1 day. |
|
security (Security Scanning) |
quality |
npm audit --omit=dev --audit-level moderate (runtime dependencies), npm audit --audit-level high (all), and a Snyk scan at high severity that does not fail the build. |
docker (Docker Build & Push) |
quality, security |
Build the linux/amd64 and linux/arm64 image and push it to GHCR (not on pull requests), then load a local nsf-awards-mcp:test image and smoke-test it. |
release (Create Release) |
quality, security, docker |
Only on v* tags. See Releasing. |
deploy-staging (Deploy to Staging) |
quality, security, docker |
Only on pushes to main. A placeholder that only prints messages. See Releasing. |
deploy-production (Deploy to Production) |
quality, security, docker, release |
Only on v* tags without rc, beta or alpha in the name. A placeholder that only prints messages. See Releasing. |
The Docker smoke tests send an MCP initialize request with protocol version 2025-11-25 and
require "name":"nsf-awards-mcp" in the response. Over stdio:12
RESPONSE=$( (printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"ci","version":"1"}}}'; sleep 5) \
| docker run --rm -i -e LOG_LEVEL=error nsf-awards-mcp:test)
Over HTTP, the job starts the container with MCP_TRANSPORT=http on port 3000, polls
http://localhost:3000/health for up to 20 seconds, then POSTs the same initialize request to
http://localhost:3000/mcp with Accept: application/json, text/event-stream.12
Live NSF API (live-api.yml)
Runs every Monday at 09:00 UTC (cron: '0 9 * * 1') and on manual dispatch, with read-only
permissions, no secrets, a 30-minute timeout and a live-api concurrency group that does not cancel
a running job.2 Steps: Node 22, npm ci, npm run test:live (which builds), then
node scripts/validate-live.mjs.
Dependency updates (dependency-update.yml)
Also runs every Monday at 09:00 UTC and on manual dispatch.13 It runs
npm audit --audit-level high, npm outdated and Snyk. On main it runs npm update, and if
package-lock.json changed it runs npm ci, npm run type-check, npm test and npm run build,
then opens a chore: automated dependency updates pull request from the
automated-dependency-updates branch. It also reports the Node base image in the Dockerfile and
checks dependency licenses with license-checker.