Adding or changing a tool
Guide
The steps, contracts and checklist for adding a new MCP tool to nsf-awards-mcp or changing an existing one.
A tool in this server is a plain object with a name, a title, a description, a Zod input schema, a Zod
output schema and an async handler. src/server.ts registers it with read-only annotations and wraps
whatever the handler returns as an MCP result.1 Adding a tool therefore touches four
places in src/ (schemas, the tool module, the export, the registration), plus tests and docs.
This page gives the steps, the contracts a handler must meet, the reusable schema pieces, and a checklist of the places that list every tool by name. For the existing tools, see Tools. For where a tool sits in the request path, see Request flow.
Steps
- Schemas. In
src/types/mcp-tools.types.ts, add a Zod input schema and an output schema. Put.describe()on every input field, because the descriptions are what the model reads. Reuse the shared pieces (see Reusable schema pieces) and add.superRefine(checkRanges)when the input has ranges.2 - Tool module. Write
src/tools/<tool>.tsand export aToolDefinition(template below). Return plain data;server.tswraps it. Search tools should returnbuildSearchOutput(...)so they share the result envelope and paging hint.2 - Export and register. Export the tool from
src/tools/index.ts, and register it increateServer()insrc/server.tswithregisterTool(server, yourTool).2 - Update the tool lists. Several tests and scripts assert the exact set of tool names (see the checklist).
- Test with fixtures (see Testing), and add a live check if the tool uses new API parameters.2
- Document it in
USAGE.md(parameters and output) andREADME.md(the tools table). If it changes behaviour that assistants should know about, updateSERVER_INSTRUCTIONSinsrc/server.ts.2
Tool module template
This is the template from the developer guide. It looks up one award and reports a missing one as an error:2
import { YourToolSchema, YourToolOutputSchema } from '../types/mcp-tools.types.js';
import { nsfApiClient } from '../client/nsf-api-client.js';
import { NotFoundError, type ToolDefinition } from './shared.js';
export const yourTool: ToolDefinition<typeof YourToolSchema, typeof YourToolOutputSchema> = {
name: 'your_tool',
title: 'Your Tool',
description: 'What it does and when to use it.',
inputSchema: YourToolSchema,
outputSchema: YourToolOutputSchema,
handler: async (input, ctx) => {
const award = await nsfApiClient.getAward(input.awardId, { signal: ctx?.signal });
if (!award) {
throw new NotFoundError(`No NSF award found with ID ${input.awardId}`);
}
return { award };
}
};
Relative imports in src/ end in .js, because the package compiles with module:
NodeNext.1 For real examples, compare get-award-details.ts (one lookup) and
search-by-institution.ts (a search that maps inputs to API parameters and returns
buildSearchOutput).3
The tool contract
ToolDefinition in src/tools/shared.ts has this shape:4
export interface ToolDefinition<I extends z.ZodType = z.ZodType, O extends z.ZodType = z.ZodType> {
name: string;
title: string;
description: string;
inputSchema: I;
outputSchema: O;
handler: (args: z.output<I>, ctx?: ToolContext) => Promise<z.output<O>>;
}
Input is already validated. The SDK validates arguments against the input schema and applies
defaults before the handler runs, so handlers must not parse them again.1 Invalid
arguments never reach the handler: the client gets an error result such as
Input validation error: Invalid arguments for tool search_by_pi: lastName: ....5
Cancellation. ctx.signal is the request’s AbortSignal. Pass it to every client call
({ signal: ctx?.signal }) so a client cancellation reaches axios.41
Return data or throw. The registration wrapper in server.ts does the rest:6
- On success it returns
structuredContentset to the data plus a text block with the same data as JSON. If the data has a stringhint(as everybuildSearchOutputresult does), it adds a second text block with that hint. The hint lives in the data because some clients, Claude Code among them, forward only the structured content or the first block to the model. - On a thrown error it returns
isError: truewith the error message as the only text block. ThrowNotFoundErrorfromtools/shared.tsfor a missing award or report. - It logs
Tool call completedorTool call failedwith the tool name and duration.
For the exact result and error shapes, see Search results and Errors.
Annotations are fixed. Every tool is registered with the same annotations:6
| Annotation | Value |
|---|---|
title |
the tool’s title |
readOnlyHint |
true |
destructiveHint |
false |
idempotentHint |
true |
openWorldHint |
true |
A tool that writes anything would not fit this registration. See MCP protocol.
Output schemas are loose on purpose. The client validates structuredContent against the output
schema, so a strict schema would turn upstream data drift into tool errors. The existing schemas use
z.looseObject and mostly optional fields.1 AwardRecordSchema, for example, is a
z.looseObject in which every field is optional.7
Reusable schema pieces
src/types/mcp-tools.types.ts defines these spreadable pieces for input schemas.7 They
are module-private constants, so a new schema has to live in the same file to use them.
| Piece | Fields | Rules |
|---|---|---|
pagination |
offset, limit |
offset: integer 0 to 9999, default 0. limit: integer 1 to 25, default 25. |
output |
detail, printFields |
detail: summary or full, default summary. printFields: comma-separated field names. |
status |
status |
active, expired or all; optional. |
startDates |
startDateFrom, startDateTo |
Date strings checked by nsfDate. |
expDates |
expDateFrom, expDateTo |
Date strings checked by nsfDate. |
estimatedAmounts |
estimatedTotalAmtFrom, estimatedTotalAmtTo |
Non-negative numbers in US dollars. |
Two helpers build single fields:7
nsfDate(description)is an optional string that must normalize to an NSF date. Otherwise it fails withInvalid date: expected mm/dd/yyyy or yyyy-mm-dd. The field description gets ` (mm/dd/yyyy or yyyy-mm-dd)` appended.amount(description)is an optional non-negative number, described as<description> in US dollars.
checkRanges rejects reversed ranges for the date pairs startDateFrom/startDateTo,
expDateFrom/expDateTo and dateStart/dateEnd, and for the amount pairs
estimatedTotalAmtFrom/estimatedTotalAmtTo and fundsObligatedAmtFrom/fundsObligatedAmtTo.
The issue is reported on the To field with a message such as
startDateFrom (01/01/2021) is after startDateTo (01/01/2020) or
estimatedTotalAmtFrom (5) is greater than estimatedTotalAmtTo (1).7 The schemas
reject bad dates and reversed ranges up front so that a typo errors instead of silently widening a
search.1
Award ids use a shared awardId field: a trimmed string matching ^\d{1,10}$, with the message
Award IDs are numeric (e.g. 2632685).7
For how these parameters behave for callers, see Shared search parameters.
Mapping tool inputs to API parameters
Tool inputs are not API parameters. Handlers translate the friendlier names:1
| Tool input | NSF API parameter |
|---|---|
startDateFrom, startDateTo |
startDateStart, startDateEnd |
expDateFrom, expDateTo |
expDateStart, expDateEnd |
limit |
rpp |
status (and the deprecated includeExpired) |
ActiveAwards or ExpiredAwards |
Use statusParams(status, includeExpired) from tools/shared.ts for the status mapping. It returns
{ ActiveAwards: true } for active, { ExpiredAwards: true } for expired, and nothing for all.
When status is absent, includeExpired: false means active.4
The client handles everything else about the upstream API: date normalization, rpp clamping,
phrase quoting, error notifications and retries. A tool does not need to repeat
it.1 See NSF API client.
New API parameters. Add a parameter to NSFSearchParams in src/types/nsf-api.types.ts only
after you check it against the live API. The API answers unknown names with HTTP 200 and
AwardAPI-002, and it accepts some names that it then ignores.2 The comment on
NSFSearchParams lists the names known to be rejected or useless.8 For the verified
parameter list and how to probe a new one, see Search parameters
and Testing.
Search tools
A search tool should call the client, then pass the result to buildSearchOutput together with the
tool’s offset, limit, detail and printFields:4
return buildSearchOutput({
...result,
offset: input.offset,
limit: input.limit,
detail: input.detail,
printFields: input.printFields
});
buildSearchOutput shapes each award (printFields projection, full record, or summary), computes
returned, hasMore, nextOffset and capped against the 10,000 record cap, and builds
pageSummary (totalEstimatedAmt, byInstitution, byProgram) over the page.4 Use
SearchOutputSchema as the output schema. The envelope is described in
Search results.
Places that list every tool
These places name every tool and must change when you add or rename one:
| File | What to update |
|---|---|
src/tools/index.ts |
The named export list and the allTools array.9 |
src/server.ts |
A registerTool(server, yourTool) line in createServer().6 |
tests/server/server.test.ts |
TOOL_NAMES; the tools/list test expects exactly these names, sorted.10 |
tests/server/http.test.ts |
The inline name list in the lists the five tools test (sorted), checked over Streamable HTTP.10 |
tests/live/mcp.live.test.ts |
TOOL_NAMES, checked the same way against the built server.10 |
scripts/validate-live.mjs |
TOOLS (compared as sorted JSON) and, if wanted, a case in cases.11 |
USAGE.md, README.md |
Parameters, output, the tools table, and the tool count (README.md “5 read-only tools”, USAGE.md “lists 5 tools” and “All five tools”).21213 |
CLAUDE.md |
The project overview names the five tools and gives their count.1 |
DEVELOPMENT.md |
The project layout says server.ts registers “the 5 tools”.2 |
The tools/list test in server.test.ts also checks that every tool has a non-empty title, a
description longer than 20 characters, object input and output schemas, and the read-only
annotations.10
Testing a new tool
- Add
tests/tools/<tool>.test.ts. Build data fromtests/fixtures/throughnormalizeAward, and mock withjest.spyOn(nsfApiClient, ...). - Call the handler with
Schema.parse(input)or a complete object, because handlers expect validated input. - Add schema cases to
tests/tools/schemas.test.ts(defaults, bounds, rejected input). - Add protocol cases to
tests/server/server.test.ts, which run on both protocol eras. - If the tool uses new API parameters, add a live check in
tests/live/.