Context
Tools use the tool() builder from @cyanheads/mcp-ts-core. Each tool lives in src/mcp-server/tools/definitions/ with a .tool.ts suffix. The standard registration pattern uses a definitions/index.ts barrel that collects all tools into an allToolDefinitions array for createApp(). Fresh scaffolds from init start with direct imports in src/index.ts — the barrel is introduced as definitions grow. Match the pattern already used by the project you're editing.
Steps
- Gather the tool's name, purpose, and input/output shape from the user's request — ask only if genuinely absent
- Determine if it needs input the caller may not supply — a confirmation, a choice, the client's roots — which makes it a multi-round-trip handler (
ctx.requestInput/ctx.inputs, seeapi-context) - Create the file at
src/mcp-server/tools/definitions/{{tool-name}}.tool.ts - Register the tool in the project's existing
createApp()tool list (directly insrc/index.tsfor fresh scaffolds, or via a barrel if the repo already has one) - Run
bun run devcheckto verify — it applies Biome's formatting fixes as it runs - Smoke-test with
bun run rebuild && bun run start:stdio < /dev/null(orstart:http) — theCore services constructedlog record must list the new tool in itstoolsfield (the message text shows only counts); if it doesn't, the tool never reachedcreateApp()
Naming
Tools use lowercase snake_case with a canonical server/domain prefix, {server}_{verb}_{noun} by default. Drop the noun only when the verb is a complete action on its own (git_pull, git_status): if {server}_{verb} leaves "…what?" unanswered — search what? connect to what? — the noun is missing. The full rule is the Name row of the design-mcp-server Design table.
Examples: pubmed_search_articles, pubmed_fetch_fulltext, clinicaltrials_find_eligible.
The server prefix is judged on clarity, not length: the brand name or the plain well-known word for the domain both pass (pubmed_, patents_); an abbreviation fails only when it reads as something else out of context (loc_, ct_). A fourth segment is fine when the noun is inherently two words (openfda_search_device_clearances). When a name resists the schema — can't pick a verb, noun feels generic, the verb wants a second word — that's usually a signal the scope is fuzzy; split the tool, rename, or reconsider.
For shape selection (Workflow, Instruction, or Reference variants — standard single-action tools are the default), see the design-mcp-server skill's Tool shapes section.
Template
/**
* @fileoverview {{TOOL_DESCRIPTION}}
* @module mcp-server/tools/definitions/{{TOOL_NAME}}
*/
import { tool, z } from '@cyanheads/mcp-ts-core';
import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
export const {{TOOL_EXPORT}} = tool('{{tool_name}}', {
title: '{{TOOL_TITLE}}',
// Single cohesive paragraph — pack operational guidance into prose sentences,
// not bullet lists or blank-line-separated sections. Descriptions render inline.
description: '{{TOOL_DESCRIPTION}}',
annotations: { readOnlyHint: true },
input: z.object({
// All fields need .describe(). Only JSON-Schema-serializable Zod types allowed.
}),
output: z.object({
// All fields need .describe(). Only JSON-Schema-serializable Zod types allowed.
}),
// Agent-facing context on the success path — empty-result notices, the query as
// the server parsed it, pagination totals. The counterpart to errors[]: merged
// into structuredContent AND mirrored into content[] automatically (no format()
// entry needed, never touched by format-parity). Populate via ctx.enrich(...) in
// the handler or service layer. Keys must be disjoint from output. Delete if unused.
enrichment: {
effectiveQuery: z.string().describe('The query as the server parsed it.'),
totalCount: z.number().describe('Total matches before any limit was applied.'),
},
// auth: ['tool:{{tool_name}}:read'],
// Each entry declares a domain-specific failure mode and types
// `ctx.fail(reason, …)` against the declared union. Baseline codes
// (InternalError, ServiceUnavailable, Timeout, ValidationError,
// SerializationError) bubble freely — only declare domain-specific reasons.
// Delete this block if no domain failures apply.
//
// Keep contracts inline on this tool, even when other tools have similar
// entries. The contract is part of the tool's documented public surface —
// don't extract a shared `errors[]` constant; per-tool repetition is the
// intended cost of self-contained tool defs.
//
// `recovery` is required (≥ 5 words) — it's the agent's next move when this
// failure fires. Forcing function for thoughtful guidance: placeholders like
// "Try again." get flagged by the linter. The contract `recovery` is the
// single source of truth for what flows to the wire — the framework sends it
// with any failure carrying the reason and no hint of its own.
errors: [
{ reason: 'queue_full', code: JsonRpcErrorCode.RateLimited,
when: 'Local queue at capacity.', retryable: true,
recovery: 'Wait a few seconds before retrying or reduce batch size.' },
],
async handler(input, ctx) {
ctx.log.info('Processing', { /* relevant input fields */ });
// Pure logic — throw on failure, no try/catch.
// With an `errors[]` contract: `throw ctx.fail('reason_id', message?, data?)`.
// Without: throw via factories (`notFound`, `validationError`, …) or plain `Error`.
const items = await search(input);
if (queue.full()) {
// Static recovery — the string lives in errors[] above, and the framework
// puts it on both client surfaces as `data.recovery.hint`.
throw ctx.fail('queue_full');
}
// Surface what the agent reasons with — echoed query, true total — on BOTH
// client surfaces, with no format() plumbing. An empty result is a notice,
// not a throw: reserve ctx.fail for genuine failures (queue full, upstream down).
ctx.enrich.echo(input.query);
ctx.enrich.total(items.length);
if (items.length === 0) {
ctx.enrich.notice(`No items matched "${input.query}". Try broader terms or check the spelling.`);
}
return { items };
},
// format() populates MCP content[] — the markdown twin of structuredContent.
// Different clients read different surfaces (Claude Code → structuredContent,
// Claude Desktop → content[]), so both must carry the same data.
// Enforced at lint time: every field in `output` must appear in the rendered text.
format: (result) => {
const lines: string[] = [];
// Render each item with all relevant fields — not just a count or title.
// A thin one-liner (e.g., "Found 5 items") leaves the model blind to the data.
for (const item of result.items) {
lines.push(`## ${item.name}`);
lines.push(`**ID:** ${item.id} | **Status:** ${item.status}`);
if (item.description) lines.push(item.description);
}
return [{ type: 'text', text: lines.join('\n') }];
},
});
Multi-round-trip variant
A handler that needs something the caller didn't supply returns ctx.requestInput(...) and is re-entered with the answers on ctx.inputs. There is no mid-handler await for user input, and no capability check — the surface is always present, on every transport and both protocol eras. Whether the caller can answer is a separate question — a 2025-era HTTP client cannot when the server runs MCP_SESSION_MODE=stateless, which a server needing that leg declares with createApp({ sessionMode: { require: 'stateful' } }) rather than leaving to a deployment (api-context § ctx.requestInput). Treat an unanswered round as terminal, never as consent.
import { inputRequired, tool, z } from '@cyanheads/mcp-ts-core';
import { validationError } from '@cyanheads/mcp-ts-core/errors';
const Choice = z.object({ region: z.enum(['us', 'eu']).describe('Region to deploy to.') });
export const {{TOOL_EXPORT}} = tool('{{tool_name}}', {
description: '{{TOOL_DESCRIPTION}}',
input: z.object({ /* ... */ }),
output: z.object({ /* ... */ }),
handler(input, ctx) {
// A declined or cancelled prompt is a dead end — don't re-ask it.
const view = ctx.inputs.view('region');
if (view.kind === 'elicit' && view.action !== 'accept') {
throw validationError(`User ${view.action} the region prompt.`);
}
// Read what a prior round collected before asking for anything.
const answer = ctx.inputs.accepted('region', Choice);
if (!answer) {
return ctx.requestInput({
inputRequests: {
region: inputRequired.elicit({ message: 'Which region?', requestedSchema: Choice }),
},
});
}
// `answer` is narrowed here.
return { /* output */ };
},
});
A confirmation before a destructive step is different. ctx.inputs only carries response kinds the client declared, but a client that declared elicitation can still send an "accepted" answer on a call nothing asked, and any requestState replays within its lifetime. A consent gate stores { operation, clientId, subject, target, contentHash } in ctx.state under a random id, sends only that id as requestState, redeems the record before anything else in the handler, and asks again on an unknown, used, or expired id or on any field that differs from this call — the full handler, and the concurrency limit an action that must not repeat has to design around, are in api-context § Consent gates. Pair it with MCP_REQUEST_STATE_KEY so a retry can only carry state this server minted.
Write it as return ctx.requestInput(...) — the never return type makes it valid in return position for any output, and it is what lets TypeScript narrow the line below. Full reference (inputRequired.elicitUrl / .createMessage / .listRoots, requestState, decline handling): framework-skills/api-context.
Registration
// src/index.ts (fresh scaffold default)
import { createApp } from '@cyanheads/mcp-ts-core';
import { existingTool } from './mcp-server/tools/definitions/existing-tool.tool.js';
import { {{TOOL_EXPORT}} } from './mcp-server/tools/definitions/{{tool-name}}.tool.js';
await createApp({
tools: [existingTool, {{TOOL_EXPORT}}],
resources: [/* existing resources */],
prompts: [/* existing prompts */],
});
If the repo already uses src/mcp-server/tools/definitions/index.ts, update that barrel instead of switching patterns midstream.
Feature-flagged tools (disabledTool wrapper)
When a tool is gated behind config (e.g., BRAPI_ENABLE_WRITES, FOO_PRO_FEATURES), the gate has two failure modes when wired naively. Excluding the tool from the array hides it from MCP registration and from the HTTP landing page — operators see a smaller catalog than the README documents and have no in-page hint that the tool exists at all. Always registering it lets clients call the tool and forces handler-side forbidden throws, which keeps the dangerous surface in the LLM's reach.
disabledTool() resolves this: the wrapped tool is present in the manifest and rendered on the landing page (muted card, with a reason and an optional hint for how to enable it), but skipped during MCP server registration so clients cannot call it.
import { disabledTool, tool, z } from '@cyanheads/mcp-ts-core';
import { getServerConfig } from '@/config/server-config.js';
const submitObservationsDef = tool('brapi_submit_observations', {
description: 'Submit observation records (POST/PUT) with elicit gate.',
annotations: { readOnlyHint: false, destructiveHint: false },
input: z.object({ /* … */ }),
output: z.object({ /* … */ }),
async handler(input, ctx) { /* … */ },
});
export const submitObservations = getServerConfig().enableWrites
? submitObservationsDef
: disabledTool(submitObservationsDef, {
reason: 'Writes are turned off in this deployment.',
hint: 'BRAPI_ENABLE_WRITES=true',
});
DisabledMetadata shape: { reason: string; hint?: string; since?: string }. The reason renders as a sentence on the disabled card; hint (when present) renders as a code-styled block — use whatever the gate is (env var line, config key, doc reference). since annotates the card with a small "since vX" tag — useful when phasing a tool out behind a flag before removal.
Three tool listings to keep straight:
| Surface | Disabled tools? |
|---|---|
tools/list (MCP protocol — what clients call) |
No — disabled tools are skipped at registration |
/.well-known/mcp.json (Server Card) |
No — the card carries no per-tool entries at all, so a discovery agent reading it cannot see a disabled tool |
/ (HTML landing page) |
Yes, in a 4th muted bucket after read | write | destructive — the only surface where a disabled tool is visible |
The wrapper preserves all original definition fields (handler, schemas, auth scopes, error contracts) — when re-enabled, the tool already conforms to every lint rule.
Audit what still names the tool
Gating a tool removes it from tools/list, but nothing rewrites the rest of the server. Every reference that survives points a client at a name it cannot call. Sweep for the tool's name across three surfaces and fix what the gate makes wrong:
| Surface | What the gate requires |
|---|---|
Static prose — server instructions, tool descriptions, field .describe() text |
Do not describe a disabled tool as currently callable. |
Recovery text — errors[].recovery, ctx.fail hints, ctx.enrich notices, service summaries |
Offer an available next step, or say the capability is unavailable in this deployment. |
Structured suggestions — nextToolSuggestions, or any { toolName, args } entry a client executes |
Emit a suggestion only when its target is enabled under the same configuration. |
A suggestion is executable; prose is not. When no callable alternative exists, prose may still explain the limitation — but the executable entry goes:
const { enableWrites } = getServerConfig();
// The suggestion is emitted only under the config that registers its target.
const nextToolSuggestions = enableWrites
? [{ toolName: 'brapi_submit_observations', reason: 'Record the observations collected for this study.', args: { studyDbId } }]
: [];
return {
observations,
nextToolSuggestions,
...(enableWrites
? {}
: { notice: 'Submitting observations is turned off in this deployment.' }),
};
The same audit applies to a tool's own errors[].recovery: a hint naming a tool that this deployment gates off sends the agent to a dead end at exactly the moment it is recovering from a failure.
Schemas: what the framework stores vs. what clients see
tool() and the handler factory do not hand your Zod schemas to the SDK verbatim. Two deliberate transforms sit in between.
Input is strict
tool() stores input with .strict() applied, and the advertised inputSchema carries additionalProperties: false to match. An unrecognized argument key is rejected by name before the handler runs:
Input validation error: Invalid arguments for tool <name>: Unrecognized key: "querry"
That arrives as an isError: true result, not a JSON-RPC error, and produces no framework span or log. The alternative — silently stripping the key — turns a caller's typo into a wrong answer they cannot detect: the value vanishes before the handler runs and the call fails downstream pointing at the wrong problem.
Two limits worth knowing when you write a schema:
- Root level only, matching
.strict()itself. A nestedz.object()inside the input still strips unknown keys unless it is strict in its own right — mark the nested option objects you want guarded. - An explicit opening wins. A definition that declared
.passthrough()or.catchall(...)asked for an open object, andtool()leaves it alone. Use that (deliberately) for tools that proxy arbitrary upstream query parameters. - A union root is strictened per variant. See below — the branch is where the properties live, so that is where
additionalProperties: falselands.
Declare .strict() before .describe() / .meta() on the root. Zod keys both to the schema instance, and .strict() clones without it — so z.object({…}).describe('…') loses the description when tool() strictens, and the advertised inputSchema carries none. z.object({…}).strict().describe('…') keeps it, because an already-strict schema is returned untouched. lint:mcp reports the loss as schema-root-meta-discarded. It bites the root only (and each variant of a union root); field- and nested-level describes are unaffected.
Three things the framework fixes before the schema sees the arguments
Strict input is right for a misspelling the caller can fix, and wrong when the arguments the model wrote were correct and something between the model and the schema was not. An ordered step inside parseToolArguments covers those cases: drop client-added keys → key aliases → parse → on failure, repair and one re-parse, plus one alias-first retry when that still fails and the drop discarded a key (below). All three stages are on by default and none changes what tools/list advertises. A call they rescue carries nothing about them in its response — each change in the attempt your handler receives emits a debug log and a counter (mcp.input.ignored_key, mcp.input.aliased, mcp.input.coerced) instead, so a new client artifact surfaces in telemetry rather than as a failed call. A call they cannot rescue is rejected with the rewrites and underscore-rule drops of the order whose rejection it carries reported, as data.input and as closing hint sentences (Validated query as targetQuery., Dropped undeclared key _max.), because the issues name only the keys that were validated and the caller could not otherwise tell a bad value from a moved or discarded key. Its issues name only what still fails once the repairs that held are applied (point 3).
1. Client-added root keys are dropped. Some clients put their own keys inside arguments: a placeholder when the model sends none, a call description, a call id, or a _meta block that belongs on params. The model never wrote them and cannot remove them, so the retry fails identically. An undeclared root key is dropped when it is underscore-prefixed or on the built-in list (_meta, tool_call_description, toolCallId). Three boundaries: a declared key is never dropped (on a union root, that means every variant's keys); an author-opened root is left alone; and a tool declaring any underscore-prefixed key of its own switches the underscore rule off — otherwise a misspelled _cursor would vanish silently, which is the failure strict input exists to prevent.
2. A key alias reaches the handler under the canonical name. Declare the mappings you know:
export const drugProfile = tool('drug_profile', {
input: z.object({ drug: z.string().describe('Generic or brand name.') }),
inputAliases: { drug_name: 'drug', substance: 'drug' },
// …
});
Alongside those, an undeclared key whose case-folded form (-/_ stripped, lowercased) names exactly one declared key is rewritten too — max_results, Max-Results, and MAXRESULTS all reach a declared maxResults, with nothing declared. Neither half advertises anything: inputSchema is byte-identical with or without inputAliases, so the canonical key keeps its place in required and the model is still told to use it.
Declare an alias where the meaning is certain and the mapping is one-to-one — a sibling tool's spelling for the same concept, the upstream API's own name, a shorthand weaker models reach for. It is not fuzzy matching: a key matching no alias and no declared key is still rejected by name, with the accepted-key hint. Four boundaries: a rewrite applies only when the target key is absent (alias and target present is rejected, and the hint names the alias as one rather than as an unknown key: drug_name is an alias of drug; send one of them, not both., or send only one of them. when three or more keys for one target arrive; an _-prefixed alias the drop discards is the exception, below); an author-opened root is never rewritten; a union root resolves against the variant the discriminator selects, and rewrites nothing when the discriminator is absent or unrecognized; and a headerParam-designated target is never rewritten to — the SDK cross-checks the Mcp-Param-<Name> header against the raw body before dispatch, so a later rewrite would hand your handler a value no intermediary attested. lint:mcp rejects an alias that shadows a declared key, names a target that does not exist or is headerParam-designated, or is ambiguous against another alias or key (input-alias-conflict).
3. A representation slip in a value is repaired after the parse fails. Each repair undoes a slip the server can reverse with certainty, which is what separates a repair from the nearest-key guessing strict input refuses:
- A JSON-stringified array or object —
statusFilter: "[\"RECRUITING\"]"againstz.array(z.string()),target: "{\"type\":\"path\",\"path\":\"a.md\"}"against an object or discriminated-union field — is parsed back:JSON.parseis the exact inverse of theJSON.stringifythat produced it. A string whose trimmed form opens[or{is only ever read this way, even when it does not parse. - A safe integer sent for a string —
station_id: 8654467againstz.string()— becomes"8654467":String(n)of a safe integer is the digits the caller sent. - A string spelling a number or boolean where only those are accepted —
maxResults: "15"againstz.number(),includeMesh: "true"againstz.boolean()— becomes the one it spells. A number only whenString(n)gives the trimmed string back ("15","2.5","-3"," 15 "; never"01","1e3","1.50","0x10", or a blank), a boolean only from"true"or"false". - A lone string sent for an array —
parkCode: "yell"againstz.array(z.string())— becomes its only element, as sent. Never a blank string, and never one holding a comma or a line break: that may be a joined list, and splitting it is yours (below). nullat an optional key —sort: nullagainstz.enum([…]).optional()— is deleted, so the field reads as unset and a.default()applies. Only at a key its enclosingz.object()declares, whose field refusesnulland acceptsundefined: a required field'snull, az.record()entry, a key under a catchall, and an array element keep their rejection, and a.nullable()field receives itsnull.
The repair runs only on the failure branch, only at the paths the rejection's own issues name, once — a value one repair produced is never repaired again ("2024" against z.array(z.number()) would need the wrap and then the number repair, so it stays rejected) — and is kept only if the repaired arguments then pass your schema. A stringified value or an integer at a path Zod's own issues name is tried first, written where the caller sent it, so codes: "[\"USD\"]" against a union of a code list and a string your transform splits on commas reaches your handler as ["USD"] — beside a count: "3" sent for a number too, since that repair stays in place beside the ones that follow. Beyond that, the paths are the ones the rejection renders, so they reach inside a union field's one surviving branch exactly as the hint does: ids: [123, "a"] against z.union([z.string(), z.array(z.string())]) reaches your handler as ["123", "a"], and a literal-tagged branch is repaired where its tag matches, as long as every other branch fails on its tag alone — one that also lacks a required field of its own leaves the union as sent. A tag no variant accepts is read as a field holding every variant's tag: { kind: "1" } against variants tagged z.literal(1) and z.literal(2), in a z.discriminatedUnion() or a plain union of tagged objects, reaches your handler as { kind: 1 }, as does any field every branch of a plain union lists the values of. The gates below apply there as at any field, so "01", "3", or "1" beside a string-tagged variant keeps its rejection, and since the repaired tag selects a variant your schema never parsed, a second slip inside that variant is reported, not repaired with it. They also reach inside what a z.preprocess() made of a value: items: { name: "abc", year: 2020 } against a preprocess that wraps a lone object as a list reaches your handler as [{ name: "abc", year: "2020" }]. The repair is first written in place, at the issue path in the arguments as sent, and kept when your schema then accepts the call, so [1, 2] against a preprocess that reverses a list reaches your handler as ["2", "1"]. Otherwise it is written into the preprocess's output, and that output replaces the argument only when your preprocess, applied to it, returns it unchanged — an equal copy counts; one that reorders it or rewrites a value in it keeps the call's rejection. When two branches fail inside the value ([123] against z.union([z.array(z.string()), z.array(z.boolean())])), neither is read, and a branch that takes a number at that path is reported as its own check, which no repair takes. So it cannot touch a value that was already valid: a free-text field legitimately holding "[1,2,3]" or "{…}" is not in the issue list, so it survives untouched even when the same call carries a genuine stringified value in another field. The scalar repairs are gated further, to issues that say the value failed for its type where the other reading is the only one. An integer becomes a string only where the issue refuses a number (a wrong type, a string-only enum, a union every branch of which refused the type): -1 against z.union([z.number().int().positive(), z.string()]) keeps its rejection instead of slipping past your constraint through the string branch, and -0, a fraction, or an integer past Number.MAX_SAFE_INTEGER is never repaired. A string becomes a number or boolean only where the field takes no string and no array: "15" against z.union([z.number(), z.literal('auto')]) is a wrong string, not a number, and stays rejected. Neither that nor the list wrap applies at a field you route through .transform(), .pipe(), or z.preprocess(), nor at a key that another reading of the path routes that way — an option of a plain union, either side of an intersection, or a branch whose own tag the caller sent wrong: its rejection can describe your transform's output, so a name your lookup lacks stays rejected instead of becoming ID 15. Inside a union branch the gates read a value as a plain union of the branches would: { v: 6 } against z.union([z.object({ v: z.literal(5) }), z.object({ v: z.string() })]) stays rejected, as 6 against z.union([z.literal(5), z.string()]) does. Your schema still decides the repaired value — 20260922 against z.iso.date() and "0" against z.number().int().min(1) stay rejected. Apart from a deleted null, no key is added, dropped, or renamed. When nothing validates, the rejection is a parse of the arguments with only the repairs that held applied — those no remaining issue sits at or below. A value your schema accepted once repaired is not reported: fourteen integer PMIDs against z.array(z.string().regex(/^\d+$/)).max(10) report only pmids: Too big: expected array to have <=10 items, not fourteen Send pmids.N as a string sentences ahead of it. The exception is a value that held only written in place under a preprocess that reorders or rewrites it: [1, 2] under the reversing one, beside a field that still fails, is reported as sent, since the issues name positions in the preprocess's output. A value whose repair your schema refused is reported as sent, so a call no repair helped gets exactly what it gets under coerce: false — as does one the held repairs alone would validate (only a union or a cross-field refinement allows that), held values included — and the rejection never mentions a repair.
When the drop took a key the alias stage wanted. The drop runs first, so it also discards an underscore spelling of a declared key (_query for query), a declared inputAliases: { _q: 'query' }, and an ignore-listed key a declared alias names. If the call then fails, repair included, the step reruns both stages with the alias stage first, where those keys are rewritten instead, and keeps that retry only if it validates, again with its own repair. The retry never case-folds an ignore-listed key onto a declared one (_meta stays the client's even beside a declared meta), and still drops an underscore key it cannot resolve. It never changes which calls validate: { query: 'abc', _max_results: '12345' } against an optional maxResults: z.number() validates with _max_results dropped, so the retry never runs. A call neither order validates gets the retry's rejection, which describes the arguments as the caller meant them: { _q: 'ab' } against query: z.string().min(3) reports the too-short query and closes Validated _q as query., not a missing query beside a dropped _q. A _q sent beside query is still dropped, and when the call fails on something else the hint names it as _q is an alias of query; send one of them, not both., not as a dropped key.
Turn any stage off per server — there is no per-tool switch:
await createApp({
input: {
ignoreKeys: ['some_client_field'], // adds to the built-in list; `false` disables the stage
caseStyleAliases: false, // declared `inputAliases` only
coerce: false, // never repair an argument value
},
tools: allToolDefinitions,
});
Those three stages are the whole of the framework's input edge: argument key names, and the value shapes above — a JSON-stringified array or object, which JSON.parse inverts with certainty; a safe integer sent for a string, whose digits String(n) restores; a number or boolean sent as the string String(n) or "true"/"false" writes; a lone string sent for a list; and null sent for an optional field. Every other value normalization is domain knowledge and belongs to the tool: the case or bare-leaf form of a code, a unit or vocabulary alias, a composite identifier assembled from two arguments, a delimiter-joined list, a spelled-out name. Which variants a given input accepts is decided per input at design time (design-mcp-server § Parameter descriptions) and applied at the head of the handler, on the unambiguous mappings only.
Multi-mode tools take a discriminated-union input
When a tool has genuinely exclusive argument sets — look up by ID or search by name, never both — declare the union directly instead of making every field optional and checking the combination by hand:
const lookup = tool('lookup', {
description: 'Looks a record up by exactly one of the supported keys.',
input: z.discriminatedUnion('mode', [
z.object({
mode: z.literal('byId').describe('Look up by exact ID.'),
id: z.string().describe('Record ID.'),
}),
z.object({
mode: z.literal('byName').describe('Search by name.'),
name: z.string().describe('Name fragment.'),
fuzzy: z.boolean().default(false).describe('Whether to match loosely.'),
}),
]),
output: z.object({ /* … a flat object; see below */ }),
handler: (input) =>
input.mode === 'byId' ? byId(input.id) : byName(input.name, input.fuzzy),
});
The handler dispatches on the discriminator and TypeScript narrows input to that branch — input.id exists only under 'byId', and reaching for input.name there is a compile error.
What reaches the wire is {"type": "object", "oneOf": [<branch>, …]}: branches intact, each with its own required list and a const-tagged discriminator, additionalProperties: false on every one. Identical bytes on a 2025-11-25 and a 2026-07-28 connection — the legacy projection inspects outputSchema alone and never rewrites an input root.
Four constraints:
- The union must be discriminated. A bare
z.union(...)is rejected: with no literal-tagged key the model has nothing to choose a branch by, and every variant'srequiredwould read as applying at once. outputstays a flatz.object— see the widening section below for why a non-object output root breaks the success path. When the result shape varies by mode, use akinddiscriminator with presence-based optional fields and render each arm on field presence informat().- Claude clients flatten the union root. The Anthropic Messages API rejects a top-level
oneOfininput_schema, so Claude clients rewrite the root before the model sees it — and the rewrite keeps only the first branch's properties, withrequired: []. A tool that must work in Claude clients takes a flatz.object()with an enum discriminator, optional per-mode fields, each mode's required fields named in the discriminator's.describe(), and the combination checked in the handler.schema-root-oneof-portability(strict mode only) flags the union root. Tracked in #510. - A union root rules out
headerParam. See below — the branches sit underoneOf, which the reachability rule excludes.
headerParam mirrors an argument into a request header
Protocol revision 2026-07-28 lets a tool designate an input property with x-mcp-header, so its value also rides an Mcp-Param-<Name> request header. A proxy, gateway, or router can then read it without parsing the JSON-RPC body:
import { headerParam, tool, z } from '@cyanheads/mcp-ts-core';
input: z.object({
query: z.string().describe('Search query.'),
routing: z.object({
region: headerParam(z.string(), 'Region').describe('Deployment region.'),
shard: headerParam(z.int(), 'Shard-Id').describe('Shard the record lives on.'),
}).describe('Where to route the lookup.'),
}),
The emitted property carries "x-mcp-header": "Region" and nothing else about the field changes — description, type, validation, and requiredness are untouched. Order does not matter: headerParam(z.string(), 'Region').describe('…') and headerParam(z.string().describe('…'), 'Region') are the same schema.
It mirrors, it does not relocate. When the body carries a value for a designated property, the matching Mcp-Param-<Name> header MUST be present and decode to an equal value; the SDK cross-checks the pair before dispatch and rejects a disagreement with -32020 (HeaderMismatch, HTTP 400). Absent or null in the body means no header is expected. Your handler still reads the argument from input — there is nothing new to do in the handler body. Browser clients need nothing extra either: the HTTP transport's CORS preflight allows Mcp-Param-<Name> for every designation on a registered tool, for each origin MCP_ALLOWED_ORIGINS accepts.
Where a designation is legal. The property must be primitive-typed (string, integer, number, boolean) and statically reachable through a chain of properties keys. Top-level and nested z.object() fields qualify. These do not:
| Placement | Why |
|---|---|
An array element (z.array(z.object({ … }))) |
Lives under items |
A z.record() value |
Lives under additionalProperties |
| Any field of a discriminated-union input root | The root advertises oneOf, so every branch is off the chain — no field of a union-input tool can be designated |
A schema reused under .meta({ id }) |
Hoisted into $defs and reached by $ref |
Header names must be non-empty RFC 9110 tokens (no spaces, control characters, or HTTP delimiters) and case-insensitively unique across the whole input schema.
Violations fail at definition time. tool() throws on import, naming the field path and the reason. That is deliberate: the SDK only console.warns and registers the tool anyway, leaving conforming Streamable HTTP clients to drop it from tools/list — a tool that silently disappears with nothing reporting the gap. The linter reports the same verdict as header-param-designation for definitions assembled without the builder.
The advertised outputSchema is widened
The framework parses a successful result against the strict effective schema — output, extended with the enrichment block when one is declared — so a required field the handler never populated still fails loudly. What it advertises in tools/list is a widened projection of that schema: every success field optional, plus a declared error property describing the failure envelope.
The reason is client-side validation. A failing tool returns structuredContent: { error: … }, which can never satisfy a success-only schema; clients whose SDK validates structuredContent without first checking isError reject that envelope with -32602 before the error ever reaches the agent. Widening the advertised schema is the only fix a server can ship, because the validator runs in the caller.
The root stays type: 'object' (a discriminated union would emit anyOf with no type, which the 2025-era legacy projection rewrites — breaking the success path to fix the error path). The required list that the object form drops is recovered by an anyOf refinement in schema metadata: a result must satisfy either the success branch (success fields present, no error) or the failure branch (error present).
Practical consequence: do not read the advertised schema as the contract your handler must satisfy. output is still the contract. The widened form is emission only.
data.reason inside that envelope stays an unconstrained string. An errors[] contract covers what the handler throws, but a service it calls can raise its own reason (the SQL gate's denied_function, a parser's yaml_parse_failed), and that reaches the wire verbatim — an enum of the declared reasons would reject precisely those envelopes, recreating the -32602 the widening exists to prevent. The declared reasons are emitted as examples and spelled out in the description instead.
error is a reserved output field name. tool() throws if output or enrichment declares one: on the wire a failure is structuredContent.error, so a success payload using the same key cannot be told apart from a failure. Rename it (errorText, failureDetail).
Tool Response Design
Tool responses are the LLM's only window into what happened. Every response should leave the agent informed about outcome, current state, and what to do next. This applies to success, partial success, empty results, and errors alike.
Agent-facing context belongs in enrichment
Empty-result notices, the query/filter as the server parsed it, pagination totals — the context an agent reasons with, as opposed to the domain payload itself — must reach both client surfaces: structuredContent (from output) and content[] (from format()). Hand-authored into format() text alone, this context reaches content[] but is invisible to structuredContent-only clients (Claude Code, MCP-SDK API callers).
Declare it as an enrichment block — the success-path counterpart to errors[] — and populate it via ctx.enrich(...) (or the kind-tagged helpers ctx.enrich.notice() / .total() / .echo()). The framework merges enrichment into structuredContent, folds the block into the tool's advertised outputSchema (see Schemas), and mirrors it into a content[] trailer — both surfaces, no format() entry, never touched by
…(truncated)