Request flow

Architecture

How a tool call travels from the transport through createServer, the tool handler and the NSF API client, and how results, errors and output schemas are shaped on the way back.

Status
stable
Trust tier
unverified
Generated
claude-code/claude-opus-5-5, 2026-12-05
Tags
architectureservertoolserrorsoutput-schema

Every MCP request follows one path through the code: the transport in src/index.ts (or src/http.ts) hands the request to a server built by createServer() in src/server.ts. The server dispatches a tool call to a handler in src/tools/, which calls the shared nsfApiClient in src/client/nsf-api-client.ts, which calls the NSF Award API.1

src/index.ts  (stdio)         src/http.ts  (Streamable HTTP, /mcp)
        \                           /
         createServer()  in src/server.ts
                 |
         registerTool wrapper  ->  tool.handler(args, { signal })   src/tools/*.ts
                                          |
                                   nsfApiClient                     src/client/nsf-api-client.ts
                                          |
                     https://www.research.gov/awardapi-service/v1/

This page covers the middle of that path: how tools are defined and registered, what a handler may assume, how its return value becomes an MCP result, and the three ways a call can fail. The transport layer is in Transports, the client in NSF API client, and record shaping in Normalization.

The server factory

createServer() builds a fresh McpServer with SERVER_INFO and SERVER_INSTRUCTIONS, registers the five tools, then registers the two resource templates. It has no process or transport concerns, so the stdio entry, the HTTP entry and the tests all build identical servers from it.2

The tools are registered in this order: search_nsf_awards, get_award_details, get_project_outcomes, search_by_institution, search_by_pi. Each is registered by name through registerTool(server, tool); src/tools/index.ts also exports an allTools array, but createServer() does not use it.23

SERVER_INFO is:

Field Value
name PACKAGE_NAME from package.json (nsf-awards-mcp)
title NSF Awards
version VERSION from package.json
description Search and read U.S. National Science Foundation awards via the NSF Award API
websiteUrl https://www.research.gov/common/webapi/awardapisearch-v1.htm

The name and version come from src/version.ts, which reads package.json; it is the only version source and also feeds the client User-Agent.21 SERVER_INSTRUCTIONS is the text the server sends to the model about the API’s quirks; see MCP protocol.

Tool definitions

A tool is a plain object of type ToolDefinition<I, O> from src/tools/shared.ts:4

Field Type Meaning
name string Tool name, e.g. search_nsf_awards
title string Display title, also used as the title annotation
description string What the model reads to choose the tool
inputSchema Zod schema I Validated by the SDK before the handler runs
outputSchema Zod schema O structuredContent is validated against it
handler (args: z.output<I>, ctx?: ToolContext) => Promise<z.output<O>> Returns data or throws

ToolContext has a single optional field, signal?: AbortSignal, which is aborted when the client cancels the request.4

The schemas live in src/types/mcp-tools.types.ts. The per-tool pages are search_nsf_awards, search_by_institution, search_by_pi, get_award_details and get_project_outcomes. To add one, follow Adding a tool.

Registration and annotations

registerTool() in server.ts passes each definition to McpServer.registerTool with the same annotations for every tool:2

Annotation Value
title the tool’s title
readOnlyHint true
destructiveHint false
idempotentHint true
openWorldHint true

McpServer.registerTool has overloads that tie the callback’s result type to the specific output schema. server.ts casts it to a looser signature (LooseRegisterTool) so that one helper can register every tool.2

What a handler can assume

The SDK validates the arguments against the Zod input schema and applies its defaults before the handler runs, so a handler receives complete, typed input and must not parse it again.15 For example, offset arrives as 0 and limit as 25 when the caller left them out, and detail arrives as summary.6

Tool inputs are not API parameters. Handlers map the friendlier tool names to the names the API accepts:17

Tool input API parameter
startDateFrom / startDateTo startDateStart / startDateEnd
expDateFrom / expDateTo expDateStart / expDateEnd
limit rpp
status (and the deprecated includeExpired) ActiveAwards / ExpiredAwards via statusParams()
institutionName (search_by_institution), institution (search_by_pi) awardeeName
stateCode awardeeStateCode
city (search_by_institution) awardeeCity
firstName / lastName (search_by_pi) pdPIName="<firstName> <lastName>"; with lastName alone, pdPIName and piLastName; coPDPI for the Co-PI search

statusParams(status, includeExpired) resolves status, falling back to active when includeExpired is false and to all otherwise. It returns { ActiveAwards: true } for active, { ExpiredAwards: true } for expired, and no flag for all.4 The full parameter lists are in Shared search parameters.

From data to a tool result

A handler returns plain data. Search tools build it with buildSearchOutput(), which produces {awards, totalResults, offset, returned, hasMore, nextOffset?, capped, limit, pageSummary, hint} and shapes each record with shapeAward() (see Normalization and Search results).4

The registerTool wrapper times the call, logs Tool call completed with the tool name and elapsed milliseconds, and passes the data to toCallToolResult():2

{
  "content": [
    { "type": "text", "text": "<JSON.stringify(data)>" },
    { "type": "text", "text": "<data.hint, search results only>" }
  ],
  "structuredContent": "<data>"
}

The second text block repeats data.hint, and is appended only when data.hint is a string. buildSearchOutput() sets hint with pagingHint() (both in src/tools/shared.ts), so only the search envelope has one.24 The hint is in the data itself because some clients, Claude Code among them, forward only the structured content or the first block to the model, so a hint only in the second block never reached it.2 It reads:

Showing <returned> of <total> matching awards (offset <offset>). More results are available: call again with offset=<nextOffset>. The NSF API caps counts and paging at 10,000; narrow the search to reach the rest.

The middle sentence appears only when hasMore is true and nextOffset is defined. The last sentence and the 10000+ form of <total> appear only when capped is true.48

Errors

A tool call can fail in three places. All three reach the client as a tool result with isError: true and a text message, not as a JSON-RPC protocol error.8

Where Cause Message
Input validation (SDK, before the handler) Arguments fail the Zod input schema, e.g. a bad date, a reversed range, limit 0, a missing lastName, a non-numeric award id, a keyword with an unmatched quote or two quoted phrases The Zod issue, e.g. Invalid date: expected mm/dd/yyyy or yyyy-mm-dd, startDateFrom (06/01/2024) is after startDateTo (01/01/2024), Award IDs are numeric (e.g. 2632685), keyword has an unmatched double quote
The handler The handler or the client throws: NotFoundError, a rejected API parameter, a transport failure, a cancellation The thrown error’s message
Output validation (SDK, after the handler) structuredContent does not match the output schema Contains Output validation error

For input validation failures the handler never runs and the NSF API is not called.8

Handler errors are caught by the registerTool wrapper in server.ts. It logs Tool call failed at warn level with the tool name, message and elapsed time, and returns { content: [{ type: 'text', text: message }], isError: true }. A non-Error value is converted with String(error).2 Handlers throw NotFoundError (from tools/shared.ts) when the client returns null for a missing award or report; the client’s own error messages are listed in NSF API client and all messages in Errors.4

Output schemas are loose

The award record schema (AwardRecordSchema, and the person entries in pi/coPDPI) uses z.looseObject with optional fields on purpose. Clients validate structuredContent against it, so a strict schema would turn upstream data drift into tool errors, and the loose one lets new or missing record fields pass through. The envelopes around the records (SearchOutputSchema, AwardDetailsOutputSchema, ProjectOutcomesOutputSchema) are plain z.object schemas with required fields that the server itself fills in.16

They still check types. AwardRecordSchema expects estimatedTotalAmt and fundsObligatedAmt to be numbers, activeAwd and hasOutcomesReport to be booleans, and each coPDPI entry to be either a string (summary records) or a person object {name, email?, former} (full records). A record that skipped normalization, for example one carrying the raw string amount "1498027", fails output validation and becomes a tool error.68

Resources

createServer() also registers two resource templates, nsf://award/{id} (nsf-award) and nsf://award/{id}/outcomes (nsf-award-outcomes). Both are registered with list: undefined, so they are not enumerated. They take the first value of the id variable, call nsfApiClient.getAward or nsfApiClient.getProjectOutcomes with the request’s signal, and throw ResourceNotFoundError when the id is not all digits (^\d+$) or nothing is found. Unlike tools, a resource failure is thrown, not returned as an isError result.2

The award resource returns the full record as application/json without projectOutComesReport and the publication fields; the outcomes resource returns the plain-text report as text/plain. See nsf://award/{id} and nsf://award/{id}/outcomes.2

Logging

Logging uses winston (src/utils/logger.ts). Its console transport writes the levels the server uses (error, warn, info, debug, verbose, listed in stderrLevels) to stderr, because stdout carries the stdio protocol. Never console.log in src/.19 The level comes from LOG_LEVEL (default info); LOG_LEVEL=debug also logs every NSF API request.95 With NODE_ENV=production the logger also writes logs/error.log (errors only) and logs/combined.log, each rotated at 5 MB with at most 5 files.9 See Configuration.

Module system

The package is an ES module ("type": "module") compiled by tsc with module: NodeNext from src/ to build/, so relative imports in src/ must end in .js (for example import { createServer } from './server.js').51

Jest runs the code as CommonJS through ts-jest with isolatedModules. Its moduleNameMapper strips the .js suffix from imports, and maps src/version.ts, which uses import.meta, to tests/support/version.ts, which reads the same package.json.15 If Jest fails on import.meta, something imports src/version.ts through a path the mapper does not match; import it as ./version.js or ../version.js.5 See Testing.

  1. CLAUDE.md, Architecture section ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8

  2. src/server.ts (createServer, registerTool, toCallToolResult) ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11

  3. src/tools/index.ts ↩

  4. src/tools/shared.ts (ToolDefinition, NotFoundError, shapeAward, statusParams, buildSearchOutput, pagingHint) ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7

  5. Developer guide (Setup, Architecture, Troubleshooting) ↩ ↩2 ↩3 ↩4 ↩5

  6. Tool input and output schemas ↩ ↩2 ↩3

  7. Tool modules in src/tools ↩

  8. In-process server tests on both protocol eras ↩ ↩2 ↩3 ↩4

  9. src/utils/logger.ts ↩ ↩2 ↩3

Sources

  1. src/server.ts (createServer, registerTool, toCallToolResult) server-source
  2. src/tools/shared.ts (ToolDefinition, NotFoundError, shapeAward, statusParams, buildSearchOutput, pagingHint) tools-shared
  3. src/tools/index.ts tools-index
  4. Tool modules in src/tools tool-modules
  5. Tool input and output schemas tool-schemas
  6. In-process server tests on both protocol eras server-tests
  7. src/utils/logger.ts logger
  8. CLAUDE.md, Architecture section claude-md
  9. Developer guide (Setup, Architecture, Troubleshooting) dev-guide