# Clerk OAuth access tokens Source: https://toolgrain.mintlify.app/authentication/clerk Protect an HTTP server with Clerk OAuth JWT or opaque access tokens. `clerk()` accepts Clerk OAuth JWT and opaque access tokens. Session tokens, API keys, and M2M tokens are intentionally excluded. Both the publishable key and secret key are required. ```ts theme={null} import { clerk, useAuth } from "@toolgrain/clerk"; import { createServer, tool } from "@toolgrain/mcp"; import { http } from "@toolgrain/node"; import { z } from "zod"; const publishableKey = process.env.CLERK_PUBLISHABLE_KEY; const secretKey = process.env.CLERK_SECRET_KEY; if (!publishableKey || !secretKey) throw new Error("Clerk keys are required"); const whoAmI = tool({ input: z.object({}), execute(_input, ctx) { const { userId, clientId, scopes } = useAuth(ctx); return { userId, clientId, scopes: [...scopes] }; }, }); const server = createServer({ name: "clerk-example", version: "1.0.0", tools: { whoAmI }, auth: clerk({ publishableKey, secretKey, scopesSupported: ["openid", "profile", "email", "offline_access"], }), }); await server.listen(http({ port: 3000 })); ``` Keep secret keys in server-side configuration. The provider derives its issuer from the publishable key. The frozen accessor result exposes `userId`, `clientId`, and readonly `scopes`, not the token or SDK client. Declare only scopes this resource intends clients to request, and ensure Clerk allows them. This catalog appears in canonical protected-resource discovery, including the direct Clerk + Elysia example. It does not require every token to contain every listed scope. See [scope configuration and troubleshooting](/guides/authorization#resource-scopes). ## Configure a client Configure a Clerk OAuth application, a public client with the appropriate redirect URI, and tokens intended for your MCP resource URL. The protected Elysia example includes manual Inspector PKCE instructions in its README. The repository's ordinary Elysia flow is credential-free on port 3003. Its separate `dev:clerk` flow uses port 3007 and reads keys from the workspace's ignored `.env.local`. Missing keys fail startup. Do not treat an unprotected example as an auth smoke test. Token verification is covered by offline JWT/opaque-token responses. The [November 8, 2026 live scope acceptance](/guides/authorization#live-scope-acceptance) verified fresh CIMD and DCR authorization, consent, refresh, and tool access with published Toolgrain 0.3.0 against a Clerk development instance. It used a self-authored acceptance client; production configurations and packaged client UIs remain unverified by that check. See [the full guide](/guides/authorization#clerk) and [Clerk reference](/reference/clerk). # JWT access tokens Source: https://toolgrain.mintlify.app/authentication/jwt Verify OAuth JWT access tokens from your trusted authorization server. Use `jwt()` from `@toolgrain/jwt` to verify access tokens from a trusted issuer. It verifies signatures, exact issuer, audience, expiration, and not-before claims. This integration does not issue tokens. ```ts theme={null} import { createServer, tool } from "@toolgrain/mcp"; import { http } from "@toolgrain/node"; import { jwt, useAuth } from "@toolgrain/jwt"; import { z } from "zod"; const whoAmI = tool({ input: z.object({}), execute(_input, ctx) { const { claims } = useAuth(ctx); return { subject: claims.sub ?? null }; }, }); const server = createServer({ name: "protected", version: "1.0.0", tools: { whoAmI }, auth: jwt({ issuer: "https://issuer.example.com" }), }); await server.listen(http({ port: 3000 })); ``` Replace the example issuer with your authorization server. Request tokens with the public MCP endpoint URL as their resource/audience. In production, configure public allowed hosts and trusted proxy handling before relying on inferred resource URLs. ## Key discovery and algorithms `issuer` is required. `jwksUrl` overrides discovery; otherwise the integration discovers the issuer's signing keys. Keys rotate and cache. Default algorithms are RS256 and ES256. Only supported asymmetric algorithms are allowed; shared-secret algorithms are rejected at construction. Standard JWT claims have typed fields. Custom claims remain `unknown`; validate them before application use. Audience arrays must contain strings, and NumericDate claims must be finite. Missing or mismatched audiences are invalid tokens and receive explicit public guidance identifying the expected resource. Actual claims and raw provider failures remain private. Unsupported token critical headers are invalid tokens; trusted key/crypto or discovery failures are provider outages rather than ordinary credential rejections. ## Further reading See [JWT API reference](/reference/jwt), the [complete authorization guide](/guides/authorization#jwt), and [apps/jwt-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/jwt-example). The example includes offline signed-token tests; it does not configure your provider's login or consent process. # Protect HTTP endpoints Source: https://toolgrain.mintlify.app/authentication/overview Protect HTTP endpoints with verified access tokens and request identities. Configure authorization on `createServer({ auth })`. Verification happens before body parsing, tool execution, and lazy provider resolution. Tools remain reusable and `ToolContext` stays non-generic. Choose [JWT](/authentication/jwt) for trusted OAuth JWT access tokens, [Clerk](/authentication/clerk) for Clerk OAuth access tokens, or implement the [provider contract](/reference/auth) for another verifier. ## Authentication is not tool policy The provider verifies a token and exposes a frozen request identity. Your application still decides which user may perform each action. Tool annotations and self-reported client metadata are not authorization checks. Per-tool scope-policy configuration is not part of the current API. Read the verified identity inside a tool or provider: ```ts theme={null} import { useAuth } from "@toolgrain/clerk"; // Inside execute(input, ctx): const { userId, scopes } = useAuth(ctx); ``` The integration's accessor is synchronous and provider-specific. It rejects contexts without the matching identity. Raw tokens and Clerk SDK methods are not exposed. ## Resource and metadata The resource is the endpoint's public URL, excluding queries and preserving its path. HTTP adapters infer it from validated request URLs unless the provider supplies an explicit resource. Audience checks, metadata, and Bearer challenges use the same value. Combined handlers automatically route public GET/HEAD protected-resource metadata. Mount them at the root; for filesystem routers, add the explicit metadata route. Bearer headers are the only credential source; query tokens are rejected. ## Client login Use an OAuth authorization server to issue access tokens for the endpoint resource. Configure a public client and its redirect URI in that provider, then use the MCP client's supported login flow. The Clerk Elysia example documents an Inspector PKCE setup. Live OAuth login remains a separate verification gap in the client report; synthetic bearer checks do not establish an end-to-end login pass. Toolgrain does not implement token issuance, login, consent, client registration, or token storage. Auth-configured servers require request transports such as HTTP and reject stdio. See the [complete authorization guide](/guides/authorization) for routing, custom providers, HTTP status behavior, and direct-call scopes. # Client interoperability — 2026-10-22 Source: https://toolgrain.mintlify.app/compatibility/clients Dated client interoperability findings and known timeout and presentation limits. Tested Toolgrain commit `3ac65d6a29df129795f682477c55828d0351491a` on macOS arm64, using Node 24.20.0 and Bun 1.3.14. The existing examples and additional temporary fixtures import the compiled workspace packages. No library implementation was changed during this review. Discovery, schema listing, ASCII/Unicode greetings, tool variants, rich results, request-cached context providers, public errors, private unexpected errors, and HTTP bearer identity work in the tested Codex and Claude Code clients. Two client behavior limitations were reproduced; neither is a malformed Toolgrain wire response. ## Results | Client/configuration | Stdio | HTTP | Protected HTTP | Revision | | - | - | - | - | - | | Inspector 2.11.0, explicit modern | Pass | Pass | Not tested | `2026-07-28` | | Inspector 2.11.0, explicit legacy | Pass | Pass | Not tested | `2025-06-18` | | Inspector 2.11.0, automatic discovery | Pass | Pass | Not tested | `2026-07-28` | | Codex CLI/app-server 0.163.0-alpha.10.2, default | Pass with timeout limitation | Pass with timeout limitation | Pass with timeout limitation | `2025-06-18` | | Same Codex, modern flag and stdio marker | Pass with timeout limitation | Pass with timeout limitation | Pass with timeout limitation | `2026-07-28` | | Same Codex, modern flag without stdio marker | Pass with timeout limitation | Pass with timeout limitation | Pass with timeout limitation | Legacy stdio; modern HTTP | | Claude Code 2.1.191, default | Pass with rich-result limitation | Pass with rich-result limitation | Pass with rich-result limitation | Negotiates down to `2025-06-18` | | Same Claude Code, explicit v2/auto negotiation probe | Same result | Same result | Same result | Still `2025-06-18` | | Cursor Agent CLI 2026.10.19-6bbf2c4 | Discovery/listing pass | Discovery/listing pass | Discovery/listing pass | Negotiates down to `2025-06-18` | Inspector passes all 30 existing checks. Codex passes 93 of 102 assertions; the other nine reproduce the same timeout limitation across three configurations and three transports. Claude Code passes 30 of 33 assertions in each of two runs; the other three reproduce the same rich-result limitation across transports. Both tested workarounds for that limitation pass in all three transports. Cursor passes four discovery/authentication checks; that CLI review did not test execution or cancellation. See the later [desktop follow-up](#cursor-desktop-follow-up). Four explicit cancellation/disconnect controls and three Claude Code timeout-response checks also pass. ## Issues ### P2: Codex direct tool-call timeouts do not promptly cancel server work Reproduction: 1. Set `tool_timeout_sec = 2` on the configured MCP server. 2. Call a tool through `mcpServer/tool/call` whose handler waits ten seconds and records an event when `ctx.signal` aborts. 3. The app-server call fails with `timed out awaiting tools/call after 2s`. 4. No handler abort occurs within the following three seconds. This occurs in all nine client/transport combinations. The stdio capture contains no `notifications/cancelled` for these requests. The HTTP connections remain active through the observation window; a pending handler aborts when the test client is subsequently closed. A client deadline therefore does not provide a matching server execution deadline in this app-server path. Positive controls through the same fixtures pass: an explicit stdio cancellation aborts the handler and suppresses its response, and disconnecting an HTTP request aborts its handler in both revisions. This distinguishes the observed client behavior from a server cancellation or forwarding-fixture fault. Claude Code's separate `MCP_TOOL_TIMEOUT=2000` probe sends `notifications/cancelled` and aborts the stdio handler. Its legacy HTTP requests also send cancellation notifications; those are advisory under Toolgrain's confirmed independent-request design and return 202. The HTTP handlers abort when that test client subsequently closes its connections. No session/client identity was introduced to correlate an independent notification with a call. Applications performing expensive work should apply their own execution deadlines. These results cover the app-server direct-call API; interactive Ctrl+C behavior was not tested. A new Toolgrain timeout API remains a separate design decision. ### P2: Claude Code hides supplemental text when structured content is present The server sends this valid tool result: ```json theme={null} { "content": [ { "type": "text", "text": "Rich report" }, { "type": "text", "text": "{\"count\":2}" } ], "structuredContent": { "count": 2 } } ``` Claude Code supplies only `{"count":2}` to its model-facing `tool_result`. The separate `Rich report` text is absent. The CLI's emitted user/tool-result event shows the same normalization. This occurs over stdio, HTTP, and protected HTTP, and is unchanged by the v2/auto environment probe on this installed build. Two workarounds were verified over every transport: * Include important narrative information in structured content, for example `{ "count": 2, "summary": "Rich report" }`. * Return text content without structured content when that is the intended contract; both text blocks then reach the model-facing result. The latter requires omitting the Toolgrain output schema, since successful explicit results with an output schema must provide structured content. These are application choices; Toolgrain should not silently discard structured output or change an application's declared schema to compensate for client rendering. ## Method and evidence Codex was driven through the installed app-server's experimental control API, using temporary configuration and ephemeral threads. No inference turn started. The three configurations match the existing compatibility report. Invalid bearer credentials were also rejected without exposing protected tools in every case. See the [official app-server documentation](https://learn.chatgpt.com/docs/app-server). Claude Code was run with `--bare --print --strict-mcp-config`, explicit temporary MCP configuration, and isolated settings. A loopback Messages API fixture emitted deterministic tool-use responses and recorded the tool results it received. The actual installed Claude Code process performed MCP discovery and execution; no paid model request, subscription credentials, or system keychain access was needed. This verifies the MCP client and its model-facing normalization, rather than a live Anthropic account/inference path. See the [Claude Code headless documentation](https://code.claude.com/docs/en/headless). Cursor's installed desktop version was 0.48.6 during that review. Its UI probe stalled and returned only an empty HTML accessibility surface, so a separate official Cursor Agent CLI release was downloaded and unpacked into the temporary test directory. The desktop installation was not upgraded. `CURSOR_CONFIG_DIR` and `NODE_COMPILE_CACHE` point to disposable test folders; only the local fixture servers were approved with `mcp enable`, then checked with `mcp list-tools`. See Cursor's [CLI installation](https://cursor.com/docs/cli/installation) and [MCP command documentation](https://cursor.com/docs/cli/mcp). Cursor lists all nine fixture tools over stdio, HTTP, and protected HTTP. It offers `2025-11-25`, accepts `2025-06-18`, and continues with POST requests after the optional HTTP event-stream GET receives 405. Invalid bearer credentials receive 401 and expose no protected tools. Its CLI subsequently reports `fetch failed` while attempting OAuth discovery against the deliberately offline authorization-server URL; a real OAuth login flow was not tested. The public MCP CLI exposes discovery/listing commands rather than direct tool execution, and no signed-in Cursor model session was started. Execution and cancellation remain unverified for that CLI build. Claude Code offered `2025-11-25` during initialization and successfully accepted Toolgrain's `2025-06-18` response. Setting `MCP_SDK_GENERATION=v2` and `MCP_PROTOCOL_NEGOTIATION=auto` did not produce a modern handshake in version 2.1.191. This is not evidence that Toolgrain supports `2025-11-25`. Current [Claude Code documentation](https://code.claude.com/docs/en/mcp#mcp-client-runtimes) describes newer builds with a v2 runtime; those builds were not tested in the 2026-10-22 review. The later [Claude Code follow-up](#claude-code-v2-follow-up) checks that runtime in version 2.1.311. The protected fixture uses a synthetic bearer token and custom `AuthProvider`. Its tool reads the verified identity using `createAuthAccessor`, and the context fixture checks that concurrent provider access shares one value per request. JWT/Clerk OAuth login, interactive GUI tool use, remote deployments, parameter header annotations, and image/audio presentation were outside the 2026-10-22 review. Local JSON evidence is stored in the ignored `reports/compatibility/` directory: * `inspector.json`: 30 CLI checks against the compiled examples. * `codex.json`: 102 assertions, observed results, and stdio/HTTP captures. * `claude.json` and `claude-v2-probe.json`: model-facing results and wire captures. * `claude-timeout.json`: timeout results and cancellation notifications. * `cursor.json`: listing output, negotiated revisions, metadata and 401 captures. * `cancellation-controls.json`: explicit cancellation/disconnect controls. * `summary-2026-10-22.json`: counts and status for each run. The harness is saved under the ignored `reports/compatibility/harness/` directory. The capture proxy uses Node's HTTP request API to preserve the external Host authority, including during protected-resource metadata discovery. These local artifacts are supplementary evidence; the table above records the tested scope and the remaining gaps. ## Cursor desktop follow-up On **2026-10-27**, Cursor desktop **3.26.16** was tested on macOS arm64 with Node **24.20.0**, Zod **4.6.7**, and freshly installed npm packages `@toolgrain/mcp` and `@toolgrain/node` **0.1.2**. Their HTTP and protocol dependencies also resolved to 0.1.2. The fixture imported installed packages, without workspace library imports. The signed-in desktop Agent performed the calls, with each tool call approved in the UI. Cursor offered `2025-11-25` and accepted `2025-06-18`. These results establish only the negotiated legacy flow, not modern Cursor compatibility or support for the originally offered revision. | Check | Result | | - | - | | Stdio Unicode greeting with declared structured output | Pass; `Hello, Cursor-雪!` reached the chat | | Stdio greeting after stopping a prior request | Pass | | HTTP Unicode greeting with declared structured output | Pass; `Hello, HTTP-雪!` reached the chat | | HTTP greeting after stopping a prior request | Pass | | Protected HTTP context call | Pass; verified synthetic bearer identity and request-cached provider value reached the chat | | Stdio Ctrl+C during a running tool | Client limitation; server work continued for 60 seconds | | HTTP Stop during a running tool | Client limitation; server work continued for 60 seconds | Five execution/recovery checks passed. The two cancellation probes are recorded as client limitations, not passing server-cancellation checks. ### Stop does not abort the tested server work To reproduce, register a `slow` tool that waits 60 seconds, records when its handler starts and when `ctx.signal` aborts, and returns `finished`. Enable the server in the workspace's `.cursor/mcp.json`, ask Agent to call `slow` once, approve the call, and stop the request while the handler is running. Keep Cursor and the MCP connection open throughout the observation window. The stdio probe used Ctrl+C; the HTTP probe used the visible Stop control. Cursor stopped the chat requests, but neither capture contained a matching `notifications/cancelled`, and neither handler observed an abort. Both handlers returned `finished` after their full 60-second wait. The HTTP request remained connected through that response. Subsequent greetings succeeded over the same connections. An earlier 10-second timing attempt finished before Stop and was excluded from the cancellation results. Four direct controls against the same published-package fixture passed: explicit stdio cancellation aborted the handler and suppressed its response in both supported revisions, and HTTP disconnection aborted the handler in both revisions. These controls distinguish the observed Cursor behavior from a Toolgrain cancellation or capture-proxy failure. Applications doing expensive work should continue to enforce their own execution deadlines. Protected HTTP used a synthetic bearer token and custom `AuthProvider`; it did not exercise live JWT/Clerk OAuth login. The additional checks below address protected HTTP cancellation, CLI/ACP execution, and modern negotiation. Live OAuth login and other GUI/result-presentation paths remain unverified. See Cursor's [MCP documentation](https://cursor.com/docs/mcp) for its current configuration and approval controls. Supplementary captures, the fixture, assertions, and the seven-check summary are stored locally under ignored `reports/cursor-2026-10-27/`. Four separate passing cancellation controls are recorded there as well. No library implementation changed during this follow-up. ### Additional Cursor client checks Later on **2026-10-27**, the same published-package fixtures were checked with Cursor desktop **3.26.16** and the official Cursor CLI **2026.10.22-27dcf5f**. The CLI used a dedicated local profile, normal Cursor sign-in, and its default Auto model through an actual [ACP session](https://cursor.com/docs/cli/acp). Only the named fixture MCP tools were approved. The CLI's [MCP discovery command](https://cursor.com/docs/cli/mcp) also listed all nine tools on each of five endpoints. | Additional check | Passed | Total | Result | | - | -: | -: | - | | Desktop protected HTTP recovery: context and Unicode greeting | 2 | 2 | Verified identity, cached context, and greeting reached the chat after Stop | | CLI discovery: legacy stdio/HTTP/protected HTTP and modern HTTP/protected HTTP | 5 | 5 | Nine tools listed per endpoint | | CLI execution: greeting and context on those five endpoints | 10 | 10 | Exact results reached the client; context confirmed each revision | | Desktop protected HTTP Stop during a running tool | 0 | 1 | Server work continued for its full 60-second wait | | Desktop modern negotiation: stdio, HTTP, and protected HTTP | 0 | 3 | The tested configuration failed to connect to the negotiation probes | | CLI modern stdio discovery | 0 | 1 | Client returned `Unsupported protocol version` | | Direct modern stdio discovery and context control | 2 | 2 | The stdio negotiation fixture accepted modern requests | The protected HTTP Stop probe sent a synthetic bearer token and negotiated `2025-06-18`. Cursor stopped the chat request, but sent no matching cancellation notification and kept the HTTP request connected. The handler observed no abort and returned `finished` after 60 seconds. The subsequent context and greeting calls passed. This extends the earlier Stop limitation to protected HTTP; it does not verify a live OAuth login. The modern negotiation fixtures rejected legacy `initialize` with error `-32022` and `data.supported: ["2026-07-28"]`, then forwarded modern requests to the unchanged published Toolgrain server. Ordinary endpoints retained both protocol eras. This fixture gate exercised client fallback; it is not a new Toolgrain server configuration API. On those HTTP probes, the CLI retried with `server/discover` and sent modern version, method, and tool-name headers and request metadata. Both modern context results confirmed `2026-07-28`; protected context included the verified synthetic identity. Ordinary stdio, HTTP, and protected HTTP instead confirmed `2025-06-18`. All five Unicode greetings reached the model's final response. The tested desktop configuration offered `2025-11-25` to both modern HTTP probes, then attempted an SSE fallback that received HTTP 405. It sent no `server/discover`. Both desktop and CLI also offered a legacy revision to the modern stdio probe and failed with `Unsupported protocol version`. These are observed client limitations, not passing modern compatibility checks. They do not establish behavior for other builds or account-controlled rollouts. Captures, the authenticated CLI transcript, and report assertions remain ignored under `reports/cursor-2026-10-27/followup/`. Cursor CLI interactive/print-mode behavior and cancellation, live JWT/Clerk OAuth login, other GUI presentation paths, and remote deployment remain unverified. ## Claude Code v2 follow-up On **2026-10-27**, the official Claude Code **2.1.311** native macOS arm64 npm package was tested in an isolated installation. The server fixture used Node **24.20.0**, Zod **4.6.7**, and freshly installed `@toolgrain/mcp` and `@toolgrain/node` **0.1.2**, with HTTP and protocol dependencies also at 0.1.2. No workspace library imports or library implementation changes were involved. Both configurations explicitly set `MCP_SDK_GENERATION=v2`. With `MCP_PROTOCOL_NEGOTIATION=auto`, Claude Code used `server/discover` and `2026-07-28` request metadata over stdio, HTTP, and protected HTTP. With `MCP_PROTOCOL_NEGOTIATION=legacy`, it initialized and negotiated `2025-06-18` over all three transports. Each transport's context tool confirmed its request revision. See the official [runtime controls](https://code.claude.com/docs/en/mcp#mcp-client-runtimes). | Configuration/check | Passed | Total | Result | | - | -: | -: | - | | v2 automatic negotiation; modern stdio, HTTP, and protected HTTP | 30 | 33 | Three cases reproduce the rich-text presentation limitation | | v2 forced legacy; stdio, HTTP, and protected HTTP | 30 | 33 | Same limitation | | Two-second tool-timeout responses across both configurations | 6 | 6 | Timeout errors reached the model-facing results | | Modern timeout cancellation, all three transports | 3 | 3 | Handlers aborted before client exit | | Legacy stdio timeout cancellation | 1 | 1 | Handler aborted before client exit | | Legacy HTTP/protected HTTP handler abort before client exit | 0 | 2 | Cancellation notifications remained advisory; disconnection later aborted the handlers | | Direct stdio cancellation and HTTP disconnect controls, both revisions | 4 | 4 | Pass | The 33 execution assertions in each configuration cover discovery/execution, ASCII and Unicode greetings, invalid inputs, a typed variant, rich results and both documented presentation workarounds, request-cached context, a verified synthetic bearer identity, public expected errors, and private unexpected errors. The six non-passing rich-result assertions are not counted as passes: the wire responses included `Rich report` alongside `{ "count": 2 }`, but Claude Code supplied only `{"count":2}` to the model-facing result. Including the narrative in structured content or returning text without structured content continued to work over every tested transport in both revisions. ### Timeout cancellation by revision The cancellation probes set `MCP_TOOL_TIMEOUT=2000` and called a tool that waits ten seconds and records `ctx.signal` aborts. The loopback model endpoint held its final response for three seconds after receiving the timeout results. This kept the Claude Code process open while checking server cancellation separately from client shutdown. In modern mode, stdio sent a matching `notifications/cancelled`, while HTTP and protected HTTP disconnected their pending requests. All three handlers observed an abort approximately two seconds after starting, and returned no successful tool result during the pre-exit observation window. In forced legacy mode, stdio cancellation also aborted its handler. HTTP and protected HTTP instead sent cancellation notifications, which Toolgrain accepted as advisory. Neither handler aborted during the additional three-second window; both aborted when the client connections subsequently closed. This preserves the independent-request contract: a legacy notification carries no safe client/session identity for cancelling another request. Applications must continue to apply their own deadlines when necessary. ### Interactive cancellation A later **2026-10-27** probe exercised the actual interactive terminal with Esc and Ctrl+C, separately, for every transport in both configurations. The fixture waited ten seconds; the harness sent a key after the handler started and kept the CLI open for three more seconds before cleanup. All **12** terminal sessions displayed `Interrupted` and remained open during that observation. | Interactive check | Handlers aborted before cleanup | Total | | - | -: | -: | | Modern stdio, HTTP, and protected HTTP; both keys | 6 | 6 | | Legacy stdio; both keys | 2 | 2 | | Legacy HTTP and protected HTTP; both keys | 0 | 4 | The eight observed aborts occurred within 81 ms of sending the key. Stdio sent matching cancellation notifications; modern HTTP disconnected the pending requests. The four legacy HTTP probes sent advisory cancellation notifications, with no handler abort or successful result during the pre-cleanup window. These are client limitations, not passing server-cancellation checks. This interactive probe used the same deterministic local model endpoint; it does not establish live Anthropic inference or other GUI behavior. ### Method and remaining limits The actual Claude Code process discovered and executed the MCP tools. A deterministic loopback Messages API fixture supplied tool-use messages and recorded the tool results returned to the model. Configuration, API credentials, and bearer identities were synthetic and isolated; no live inference or OAuth login was used. The installed user CLI and user configuration were unchanged. Explicit runtime/negotiation overrides were tested, rather than an account's feature-flag rollout or default settings. Live Anthropic inference, other GUI paths, live JWT/Clerk OAuth login, and remote deployment remain unverified. These probes do not extend Toolgrain's protocol or transport scope. Supplementary raw reports, the fixture, and assertions remain ignored under `reports/claude-2026-10-27/`. Its summary distinguishes execution assertions, client timeout feedback, server abort observations, and direct controls. # Compatibility and current limits Source: https://toolgrain.mintlify.app/compatibility/overview Separate protocol support, runtime commitments, and verified client behavior. Toolgrain targets two explicit MCP revisions. Protocol support, runtime support, and interoperability evidence are different claims: a supported protocol does not establish every client's UI or cancellation behavior. ## Protocol scope | Revision | Model | Transports | | - | - | - | | `2026-07-28` | Per-request metadata, discovery, listing, and calls | Stdio and HTTP | | `2025-06-18` | Legacy initialization-based stdio negotiation; independent legacy HTTP requests | Stdio and HTTP | Other revisions are unsupported. Legacy initialization can negotiate down to the supported older revision; this does not mean Toolgrain implements the client's originally offered revision. Modern stdio requests can interleave with legacy traffic after era selection. Modern listings include cache/server metadata and icons. Legacy results omit modern envelope metadata; listings omit icons and non-object-root output schemas. Legacy structured content is object-only; other JSON results remain text. Tool and fixed-resource lists support cursor pagination in both revisions, with a default page size of `100`. See [list pagination](/reference/mcp#list-pagination). Fixed resources implement `resources/list`, `resources/read`, and an empty `resources/templates/list` in both revisions. Lists are static; the empty template list rejects supplied cursors. Modern list/read results use `ttlMs: 0` and `cacheScope: "private"`; legacy results omit modern fields and listing icons. Resource support does not establish MCP Apps or widget rendering compatibility. See [resources](/guides/resources). ## Client evidence Inspector 2.11.0 passes the existing checks in both revisions and automatic discovery. Tested Codex tool flows work with the documented timeout limitation. The [Cursor desktop follow-up](/compatibility/clients#cursor-desktop-follow-up) verified legacy execution and recovery over stdio, HTTP, and protected HTTP in version 3.26.16. Stopping its tested calls did not abort server work on any of those transports. The [additional checks](/compatibility/clients#additional-cursor-client-checks) verified CLI execution in version 2026.10.22-27dcf5f, including modern HTTP and protected HTTP. The tested desktop configuration failed modern negotiation probes; both clients failed the modern stdio probe. The [Claude Code v2 follow-up](/compatibility/clients#claude-code-v2-follow-up) checked version 2.1.311 with explicit modern and forced legacy configurations over all three transports. Supplemental rich text remained hidden alongside structured content. Modern timeout and interactive Esc/Ctrl+C probes aborted handlers across all three transports; legacy HTTP cancellation notifications remained advisory until disconnection. The [November 8, 2026 OAuth acceptance](/guides/authorization#live-scope-acceptance) verified fresh CIMD/DCR authorization, automatic scope selection, refresh, and tool access against a Clerk development instance with published Toolgrain 0.3.0. The self-authored client used the official MCP OAuth helper 2.3.1 over loopback HTTP in both revisions. Production OAuth, packaged client login UIs, account-controlled client rollouts, other GUI flows, and remote deployment remain outside that test. See the [2026-10-22 client report](/compatibility/clients) for exact versions, assertion counts, controls, and workarounds, and [protocol verification](/compatibility/protocol) for setup and repeatable Inspector commands. Do not silently promote an old partial result into a current complete compatibility claim. ## Application requirements Node ^24.20.0 and Bun ≥1.4.4 \<2 are the supported application runtimes. Strict TypeScript 5.5.4 is the declaration floor; Zod 4 is the peer requirement. Node 26 remains preview. Hosted combinations need passing CI evidence before verification claims; see [the support policy](/project/support-policy). ## Features outside the current scope Native MCP Apps and React widgets are available in Toolgrain 0.3.0 or later. See the [host-specific acceptance record](/mcp-apps/compatibility) and [implemented/deferred message table](/mcp-apps/capabilities#react-protocol-support). Resource templates, dynamic resource discovery, prompts methods, elicitation/multi-round-trip input, subscriptions/change notifications, HTTP sessions, and resumability are separate future work. Request-scoped progress works over stdio and HTTP SSE; client UI presentation remains unverified by the dated client reports above. There is no built-in per-tool timeout API or automatic provider cleanup. Endpoint auth is implemented; token issuance and per-tool scope-policy configuration are not. # Client compatibility verification Source: https://toolgrain.mintlify.app/compatibility/protocol Recorded protocol checks, client setup, and repeatable Inspector commands. The latest published-package check is the [2026-10-25 verification](/compatibility/published-packages). Detailed [2026-10-22 interoperability findings](/compatibility/clients) cover the merged public API, context providers, protected HTTP, and observed client limitations. The dated verification below retains the earlier baseline. Verified on 2026-10-17 using Node 24.20.0 on macOS arm64. This report covers the dual-era working tree: MCP `2025-06-18` and `2026-07-28` tools over stdio and independent HTTP POSTs with JSON responses. Local reports record the checked-out base Git revision; verification can include uncommitted working-tree changes. ## Results | Client and mode | Stdio | Plain Node HTTP | Negotiated revision | | - | - | - | - | | Codex CLI/app-server 0.163.0-alpha.10.2, normal configuration | Pass | Pass | `2025-06-18` | | Same Codex build, explicit modern settings | Pass | Pass | `2026-07-28` | | Same Codex build, modern flag but no stdio marker | Pass | Pass | Legacy stdio, modern HTTP | | MCP Inspector 2.11.0 CLI, legacy mode | Pass | Pass | `2025-06-18` | | MCP Inspector 2.11.0 CLI, modern mode | Pass | Pass | `2026-07-28` | | MCP Inspector 2.11.0 CLI, automatic discovery | Pass | Pass | `2026-07-28` | Codex's normal test configuration contains neither `features.mcp_2026_07_28` nor `CODEX_MCP_PROTOCOL_VERSION`. Captured traffic starts with `initialize` requesting `2025-06-18`, then `notifications/initialized`, `tools/list`, and `tools/call`. Both transports return the expected identity and tool schema, ASCII and Unicode greetings, and `isError: true` for empty or numeric names. All six client/transport combinations across the three configurations pass, including 24 tool calls. The same HTTP example serves both eras. Modern captures confirm `server/discover`, per-request version/capability metadata, and matching HTTP routing headers. Legacy wire results omit modern `resultType` and cache fields; modern wire results retain them. CLI clients can normalize these fields before printing, so envelope assertions use raw captures and integration tests. After separating the modern and legacy modules on 2026-10-17, all client checks above pass again. A frozen build of `a235d7e` and the refactored build also produce identical results across 147 observations covering both eras, HTTP statuses and headers, malformed requests, stdio initialization, cancellation, and shutdown. Public server, transport, and HTTP declarations remain byte-identical. Modern modules have no direct or transitive dependency on legacy modules within MCP or HTTP; execution and transport behavior stay shared. ## Unified tool API verification — 2026-10-18 After moving tool authoring and execution into `@toolgrain/mcp`, Inspector 2.11.0 passes all 30 checks again over real stdio and plain Node HTTP, covering modern, legacy, and automatic discovery. Strict tool listings now also verify the title, read-only annotation, and object output schema. The Codex results above describe the earlier verification; Codex was not rerun for this API change. The library suites and six example applications pass 182 tests. Each example imports `tool` and `createServer` from `@toolgrain/mcp` and verifies metadata, output-schema discovery, and execution in both revisions. Additional server tests cover parsed/defaulted/transformed outputs, asynchronous validation, rich content, explicit errors, cancellation during output validation, and incompatible legacy metadata/output-schema omission. Compiled package/declaration checks pass, and vendor integrity remains unchanged. MCP coverage is 99.52% statements, 99.32% branches, 99.03% functions, and 100% lines. Structured error validation was also rechecked on 2026-10-18: both revisions now validate any supplied `structuredContent` against the declared output schema, including `isError: true` results. Text-only errors may omit structured data; output defaults do not create it. Regression tests cover parsed error defaults, transforms, async refinements, and `0`, `false`, and `null` payloads. All 93 MCP and 38 HTTP tests pass, as do source type checks and compiled declaration checks for valid text-only errors and rejected incompatible structured errors. Review fixes on 2026-10-19 treat undefined optional `mcpResult()` envelope and content fields, and undefined optional properties after output parsing, as absent. Undefined values inside unparsed structured data are still rejected. Text that serializes the original structured data is replaced by the parsed serialization. Tools and rich results are recognized across duplicate package copies through registered-symbol brands; spreads still lose the brand. MCP now passes 99 tests. ## Normal Codex setup Build the examples and configure the command or URL using normal MCP settings: ```sh theme={null} bun run build bun run --cwd apps/http-example start ``` ```toml theme={null} [mcp_servers.toolgrain_stdio] command = "node" args = ["/absolute/path/to/toolgrain/apps/stdio-example/dist/index.js"] [mcp_servers.toolgrain_http] url = "http://127.0.0.1:3000/mcp" ``` Use a Node version satisfying the repository's runtime requirement. Start the HTTP example separately; Codex launches the stdio command itself. No modern feature flag or per-server protocol marker is required for the tested build. Persistent user configuration was not changed during verification. ### Explicit modern verification These optional settings select `2026-07-28` in the tested Codex alpha: ```toml theme={null} [features] mcp_2026_07_28 = true [mcp_servers.toolgrain_stdio.env] CODEX_MCP_PROTOCOL_VERSION = "2026-07-28" ``` HTTP uses the feature flag; stdio also needs the marker for modern mode. Without the marker, that Codex build still connects over legacy stdio. These settings are specific to the tested alpha and may change. ## Repeat the Inspector checks Use Node 24.20.0 or a newer supported Node version and Bun 1.3.14: ```sh theme={null} bun install --frozen-lockfile bun run build --filter=@toolgrain/stdio-example... --filter=@toolgrain/http-example... node packages/repo-tools/src/cli.mjs verify-inspector ``` The command (also `bun run verify:inspector`) pins Inspector 2.11.0 through Bunx outside the workspace, runs the compiled examples using the invoking Node executable, and starts HTTP on an available loopback port. Configuration, storage, and secrets are temporary. It cleans up subprocess groups on POSIX systems, including timeouts and signals. No browser, authentication, inference, or npm publication is needed. An uncached Inspector needs registry access. To use a preinstalled copy: ```sh theme={null} node packages/repo-tools/src/cli.mjs verify-inspector --inspector-cli /absolute/path/to/inspector/clients/launcher/build/index.js ``` There are **30 passing checks**, 15 per transport: * In each era: discovery/connection, strict tool-schema listing, ASCII and Unicode greetings, empty-string and numeric-input errors, and an unlisted tool. * Automatic discovery selects modern mode on each transport. Inspector rejects unlisted tools client-side. That check does not exercise the server's unknown-tool error; package and process integration tests cover it. Inspector exits 5 for `isError: true`. Its connection-only CLI operation is named `--method initialize` in both eras; modern mode performs discovery. Interactive `inspect` scripts select modern mode; this verification script tests both. See the official [protocol-era](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/protocol-eras) and [CLI documentation](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector/cli). Runs write status, stdout/stderr, exit codes, versions, and base revision to `reports/compatibility/inspector.json`. Failures replace earlier success reports. This manual check is not added to CI and adds no MCP SDK dependency. ## Codex verification method Tests launched the installed `codex app-server --stdio` with isolated temporary configuration and an ephemeral thread. An unused loopback model provider required no authentication; no inference turn started. The control sequence was: 1. `initialize` with `capabilities.experimentalApi: true`, then `initialized`. 2. `thread/start` with `ephemeral: true`, using the temporary test directory. 3. `mcpServerStatus/list` for each server and returned `threadId`, using `detail: "toolsAndAuthOnly"`; assert connection and schema. 4. `mcpServer/tool/call` with names `Compatibility` and `Zoë 世界`; assert greetings. 5. Repeat with an empty and numeric name; assert `isError: true`. The control protocol has its own `initialize`. Separate stdio/HTTP forwarding taps capture actual MCP traffic to distinguish it. All test-owned processes were stopped. A sanitized local summary is retained at `reports/compatibility/codex.json`. ## Protocol behavior and limits * Initialization negotiates `2025-06-18`, including when a client proposes another revision. A client unable to use it must stop. This does not implement or claim the proposed revision. Modern discovery advertises the two supported revisions. * Modern metadata and HTTP routing headers remain strict. Contradictory versions are rejected. Stdio keeps legacy readiness per connection while allowing independent modern requests; HTTP selects the revision per POST without session IDs or one client's negotiated version affecting another. * Legacy HTTP initialization may omit the version header; later POSTs use `MCP-Protocol-Version: 2025-06-18`. Optional routing/parameter headers are checked when present. Valid initialized/cancelled notifications return 202 empty; GET and DELETE remain 405. * Legacy HTTP cancellation is advisory and cannot cancel another invocation: a stateless notification has no client/session identity for safe routing. Disconnects and stdio cancellation suppress delivery and abort the handler's `ctx.signal`; handlers stop early only if they observe it. * Legacy structured content contains objects only. Other JSON outputs retain their JSON text. Modern output behavior remains unchanged. The tested Codex build connects with normal settings. Claude, Cursor, other versions, GUI flows, authentication, remote deployments, and real-client cancellation were not exercised. Inspector was tested through its CLI. Framework examples have real-process checks for both eras; independent host-client tests use plain Node HTTP. Greeting has no parameter-header annotations, so real-client parameter mirroring remains outside this report. The [dual-era specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2026-07-28/basic/versioning.mdx#backward-compatibility-with-initialization-based-versions) permits both behaviors. Legacy [lifecycle](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle) and [HTTP transport](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) rules govern initialization-based calls. Root `bun run test:package` now also installs each packed library in its own npm consumer to check declared dependency resolution, runtime imports, and strict declarations. A separate full consumer checks both protocol revisions over stdio and HTTP under Node. This installation check uses the development dependency versions and offline JWT/Clerk initialization with test configuration; it does not extend the real-client compatibility claims above. Licensing and other proposed roadmap items remain separate work. # Published-package verification — 2026-10-25 Source: https://toolgrain.mintlify.app/compatibility/published-packages Recorded stable and RC archive checks and fresh package consumers. This page preserves the October 25, 2026 review. For the published 0.3.0 packages, see the [current release verification](/project/releases#current-release-status). This review checked the six published `0.1.0-rc.0` packages from `3d563791052237d205c252a3a1fefef126a45940`. Downloaded archives matched the reviewed bytes and registry integrity metadata. Stable `0.1.0` promoted the same library implementation; package manifests and READMEs changed for stable installation. The [RC0 prerelease](https://github.com/keshavkatwe/toolgrain/releases/tag/v0.1.0-rc.0) and its [release verification](https://github.com/keshavkatwe/toolgrain/actions/runs/40128994353) refer to the candidate commit. Stable `0.1.0` subsequently passed [full supported verification](https://github.com/keshavkatwe/toolgrain/actions/runs/40168972464) on `526ea39af39413d1ea2693b3961c127343b982e4`, followed by [OIDC publication and registry/consumer checks](https://github.com/keshavkatwe/toolgrain/actions/runs/40169659323). Both historical GitHub release records remain available. ## Method and results The client review used installed npm packages outside the repository, Node 24.20.0 on macOS arm64, isolated client configuration, and deterministic local API fixtures. Codex used its direct app-server tool-call API; Claude used a loopback Messages API fixture. No paid inference, live OAuth login, or persistent user configuration changes were involved. These checks do not establish production-application or interactive GUI compatibility. | Client/check | Passed | Total | Result | | - | -: | -: | - | | Inspector 2.11.0, modern/legacy/automatic discovery, stdio and HTTP | 30 | 30 | Pass | | Codex CLI/app-server 0.163.0-alpha.10.2, default/modern/mixed, stdio/HTTP/protected HTTP | 93 | 102 | Nine cases reproduce the documented timeout limitation | | Claude Code 2.1.191, stdio/HTTP/protected HTTP | 30 | 33 | Three cases reproduce the documented rich-result limitation | | Claude Code 2.1.191 timeout controls | 3 | 3 | Pass | | Direct stdio cancellation and HTTP disconnect controls, both protocol revisions | 4 | 4 | Pass | | **Total** | **160** | **172** | **No new Toolgrain blocker in the checked flows** | The 12 non-passing assertions reproduce the client limitations from the [2026-10-22 interoperability review](/compatibility/clients). They are recorded as limitations and are not counted as passing checks. ## Limitations and workarounds 1. **Codex direct-call timeout:** the tested client times out without promptly aborting server work. Applications doing expensive work should impose their own execution deadlines. Explicit stdio cancellation and HTTP disconnect controls pass in both revisions; Toolgrain cancellation remains cooperative through `ctx.signal`. 2. **Claude rich-result rendering:** supplemental text is hidden when structured content is supplied. Put essential narrative in structured content, or use text-only content where the tool contract permits it. Both workarounds pass on all three tested transports. Cursor execution/cancellation and GUI flows were unverified in this review. A later [Cursor desktop follow-up](/compatibility/clients#cursor-desktop-follow-up) checked execution and cancellation against published 0.1.2 packages, including protected HTTP Stop and [CLI execution/modern negotiation](/compatibility/clients#additional-cursor-client-checks). Modern Claude Code was also checked against 0.1.2 in the later [v2 follow-up](/compatibility/clients#claude-code-v2-follow-up), including interactive cancellation; live OAuth login remains unverified. HTTP scope is independent POST requests with JSON responses. Resources, prompts, elicitation, persistent sessions, streaming, progress, resumability, and subscriptions remain outside this release. The [compatibility guide](/compatibility/protocol) covers the earlier baseline and reproduction commands. The [support policy](/project/support-policy) defines the runtime/platform and declaration checks required for future releases. These historical results do not establish compatibility for untested clients or waive future supported regressions. # Runnable examples Source: https://toolgrain.mintlify.app/examples Find complete runnable stdio, HTTP, framework, and authorization examples. Each application is an independent workspace with its own framework dependencies and process smoke test. They import compiled library exports. From the repository root, install the pinned dependencies and build before running a selected example: ```bash theme={null} bun install --frozen-lockfile bun run build bun run --cwd apps/http-example dev ``` The repository uses Bun 1.3.14 as a development package manager. Supported Bun application execution starts at 1.4.4; use the supported runtime when evaluating production behavior. | Example | Focus | Default port | | - | - | - | | [stdio-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/stdio-example) | A full local MCP server and subprocess flow | stdin/stdout | | [http-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/http-example) | Plain Node HTTP | 3000 | | [express-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/express-example) | Node middleware mounted before body parsing | 3001 | | [hono-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/hono-example) | Web handlers with Hono's Node server | 3002 | | [elysia-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/elysia-example) | Bun/Elysia with a fixed resource, plus a separate protected Clerk variant | 3003 / 3007 | | [nextjs-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/nextjs-example) | App Router with Web handlers | 3005 | | [jwt-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/jwt-example) | Protected HTTP with JWT verification | 3006 | HTTP applications have `inspect` scripts that connect to an already running example. The stdio Inspector script launches a compiled child process. The root dev command starts every workspace watcher and example server, so use a selected workspace when you only need one application. The protected Clerk flow is explicit: `bun run --cwd apps/elysia-example dev:clerk`. It requires local keys and OAuth application configuration; ordinary Elysia dev remains credential-free. Its README covers Inspector PKCE configuration. Use [framework recipes](/transports/frameworks) for the adapter boundaries and the linked source for complete startup/shutdown behavior. Example code is teaching material, not a deployment or credential-management service. ## React MCP Apps The [React Apps example](https://github.com/keshavkatwe/toolgrain/tree/2ea4e61191c17926bb86d388c49fd5367d847d6d/apps/react-apps-example) uses Bun/Elysia with separate and shared HTML widgets. Start with the [Apps quickstart](/mcp-apps/quickstart) for Toolgrain 0.3.0 or later installation and workspace commands. Host acceptance is tracked separately from protocol tests. # Connect a client Source: https://toolgrain.mintlify.app/getting-started/clients Connect Inspector or configure an MCP client for stdio and HTTP. A server defines capabilities. An MCP client starts or connects to it, discovers tools, and issues calls. Start with Inspector to distinguish server behavior from a model's choices or a client's presentation. ## Inspector These guides use Inspector **2.11.0**, matching the repository's pin. For the compiled [stdio tutorial](/getting-started/stdio), run: ```bash theme={null} npx --yes @modelcontextprotocol/inspector@2.11.0 --cli node dist/server.js --protocol-era modern --format json --method tools/list ``` For the [HTTP tutorial](/getting-started/http), start your server separately and connect to its endpoint: ```bash theme={null} npx --yes @modelcontextprotocol/inspector@2.11.0 --cli http://127.0.0.1:3333/mcp --protocol-era modern --format json --method tools/list ``` To use the repository's complete teaching examples instead: ```bash theme={null} # Terminal 1, from the repository root: bun run --cwd apps/http-example dev ``` ```bash theme={null} # Terminal 2: bun run --cwd apps/http-example inspect ``` The HTTP example defaults to `http://127.0.0.1:3000/mcp`. The shared Inspector launcher selects the modern protocol explicitly. Select discovery, list tools, inspect the input/output schemas, and call `greet`. Reconnect after rebuilding a stdio server so the client launches the new compiled code. ## Stdio client configuration Most clients ask for an executable, an argument list, and optionally environment variables. Use absolute paths to both the executable, when needed, and the compiled server. Do not put a shell command and its arguments into one executable field. For Codex's TOML configuration, the verified legacy-compatible shape is: ```toml theme={null} [mcp_servers.hello] command = "node" args = ["/absolute/path/to/dist/server.js"] ``` Toolgrain accepts the supported legacy initialization revision without requiring a modern feature flag. Exact modern flags and tested client versions are in the [protocol verification guide](/compatibility/protocol#normal-codex-setup). Treat client-specific instructions as versioned evidence, not a promise about future clients. ## HTTP clients Use the full MCP endpoint URL, including `/mcp`. Protected endpoints additionally require the client's OAuth configuration or a valid Bearer access token. The endpoint and protected-resource metadata must be publicly reachable for remote clients; a loopback address points to the client's own machine. Toolgrain does not issue tokens or run an OAuth login UI. See [authentication](/authentication/overview) before configuring protected clients. ## What has been verified Inspector checks pass. Tested Codex and Claude Code flows work with documented timeout and rich-result presentation limitations. Cursor desktop 3.26.16 passed legacy execution and recovery checks over stdio, HTTP, and protected HTTP, with a documented limitation: stopping the tested calls did not abort server work on any of those transports. See the [dated interoperability report](/compatibility/clients#cursor-desktop-follow-up) before making a client-compatibility claim. Claude Code 2.1.311's explicit v2 runtime was also tested in modern and forced legacy modes over all three transports. Its rich-text presentation limitation remains; modern timeout and interactive cancellation aborted server work, while legacy HTTP notifications remained advisory until disconnection. See the [Claude Code follow-up](/compatibility/clients#claude-code-v2-follow-up) for the exact configuration, results, and limits. Cursor CLI 2026.10.22-27dcf5f passed greeting/context execution over legacy stdio, HTTP, and protected HTTP, plus modern HTTP and protected HTTP. The tested desktop configuration failed modern negotiation probes, and both clients failed a modern stdio probe. See the [additional Cursor checks](/compatibility/clients#additional-cursor-client-checks). # Your first HTTP server Source: https://toolgrain.mintlify.app/getting-started/http Serve the same typed tool through a managed Node HTTP listener. Keep the tool from the [stdio tutorial](/getting-started/stdio). Replace the transport to own a Node HTTP listener: ```ts src/server.ts theme={null} import { createServer } from "@toolgrain/mcp"; import { http } from "@toolgrain/node"; import { greet } from "./tools/greet.js"; const server = createServer({ name: "hello-http", version: "1.0.0", tools: { greet }, }); const transport = http({ port: 3333 }); await server.listen(transport); console.error("MCP endpoint: http://127.0.0.1:3333/mcp"); for (const signal of ["SIGINT", "SIGTERM"] as const) { process.once(signal, () => { void server.close(); }); } ``` The listener binds to `127.0.0.1` by default. The route is `/mcp`. A managed listener's default allowed hosts match loopback authorities on its actual bound port; binding and host validation are separate settings. ## Call it Compile and start the server from your project directory: ```bash theme={null} npx tsc -p tsconfig.json node dist/server.js ``` In a second terminal, use Inspector as described in [client setup](/getting-started/clients), or send a direct modern protocol call: ```bash theme={null} curl http://127.0.0.1:3333/mcp \ -H 'Content-Type: application/json' \ -H 'Accept: application/json, text/event-stream' \ -H 'MCP-Protocol-Version: 2026-07-28' \ -H 'Mcp-Method: tools/call' \ -H 'Mcp-Name: greet' \ --data '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"greet","arguments":{"name":"Ada"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}' ``` The response contains the greeting as a tool result. Modern requests include protocol metadata and capabilities on each call; this example declares an empty capability set. Tools with additional required parameter headers need those headers too. ## Existing applications If your framework owns the listener, use `createHttpHandler()` from `@toolgrain/http` for Web Request/Response, or `createNodeHttpHandler()` from `@toolgrain/node` for Node middleware. The combined handlers own MCP and auth metadata routing; mount them at the application root before body parsing. See [HTTP behavior](/transports/http) and [framework recipes](/transports/frameworks). ## Before exposing the endpoint Configure exact public `allowedHosts`, handle trusted proxy normalization in the application, and add authorization when the tools require it. `allowedOrigins` is a separate browser-origin check and does not emit CORS response headers. Applications own CORS, TLS, listener limits, and public URL normalization. HTTP uses independent POST requests with JSON responses or request-scoped SSE progress. Sessions, subscriptions, and resumability remain outside the current scope. # Installation Source: https://toolgrain.mintlify.app/getting-started/installation Install published packages and configure a strict ESM TypeScript project. Toolgrain 0.3.0 is published on npm for all seven libraries. Install matching versions across Toolgrain packages; the commands below resolve npm's `latest` tag. Apps, React, and typed content helpers are available from 0.3.0. See the [package changelogs](/project/changelog) for release notes. ## Requirements Use Node.js **24.20.0 or later within 24.x**, or Bun **1.4.4 or later within 1.x** for your application. TypeScript requires **5.5.4 or later with strict mode**; Zod requires **`^4.6.6`**. Both Classic and Mini user schemas are accepted. See the [support policy](/project/support-policy) for the complete contract. ## Install packages For a stdio server or standalone Node HTTP listener: ```bash theme={null} mkdir hello-toolgrain cd hello-toolgrain npm init -y npm pkg set type=module npm install @toolgrain/mcp @toolgrain/node zod@^4.6.6 npm install --save-dev typescript @types/node@^24.10.0 ``` For an existing Web Request/Response application, add `@toolgrain/http`. Add `@toolgrain/jwt` or `@toolgrain/clerk` when protecting HTTP endpoints. Frameworks keep ownership of their listener and application lifecycle. ## Configure TypeScript Toolgrain exports compiled ESM and declarations. CommonJS and Node's `node10` resolution mode are unsupported. For the modular tutorials, save this configuration: ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2023", "module": "NodeNext", "moduleResolution": "NodeNext", "types": ["node"], "strict": true, "outDir": "dist", "rootDir": "src", "skipLibCheck": false }, "include": ["src/**/*.ts"] } ``` Use `.js` extensions for relative imports in TypeScript intended for Node. Compile with `tsc`, then run the emitted entry point. Frameworks may own compilation and use their own supported module resolution. `@toolgrain/mcp` includes JavaScript/declaration maps and TypeScript sources for debugging and editor navigation. Public exports still resolve to compiled `dist` files. ## Develop Toolgrain itself You do not need to clone this repository to use the libraries. Repository contributors use the pinned **Bun 1.3.14** package manager, independently of the supported Bun application runtime. See [development](/project/development). Continue with the [quickstart](/quickstart) for one file, or [your first tool](/getting-started/stdio) for a modular application. # Your first tool Source: https://toolgrain.mintlify.app/getting-started/stdio Split a reusable tool and its stdio server into application modules. Create one typed tool, register it on a server, and expose it over stdio. Complete [installation](/getting-started/installation) first, including `type: module` and `tsconfig.json`. This tutorial separates the tool from the server so you can reuse it. ## 1. Define the tool ```ts src/tools/greet.ts theme={null} import { tool } from "@toolgrain/mcp"; import { z } from "zod"; export const greet = tool({ title: "Greeting", description: "Greet someone by name", annotations: { readOnlyHint: true }, input: z.object({ name: z.string().min(1) }), output: z.object({ message: z.string() }), execute: ({ name }) => ({ message: `Hello, ${name}!` }), }); ``` The handler's input type comes from the schema. A nonempty string is required; invalid input is rejected before execution. The output schema checks the returned object too. ## 2. Compose the server ```ts src/server.ts theme={null} import { createServer } from "@toolgrain/mcp"; import { stdio } from "@toolgrain/node"; import { greet } from "./tools/greet.js"; const server = createServer({ name: "hello-server", version: "1.0.0", tools: { greet }, }); await server.listen(stdio()); ``` The registration key `greet` becomes the exposed name. A definition can be reused in another server without rewriting it. `listen()` starts the transport; it does not wait for the server to shut down. ## 3. Run it through a client After compiling, configure your MCP client to launch `node` with the absolute path to `dist/server.js`. A stdio server speaks through stdin/stdout; running it in a terminal may appear to wait silently because it is waiting for protocol messages. Compile your application: ```bash theme={null} npx tsc -p tsconfig.json ``` Then call it with Inspector: ```bash theme={null} npx --yes @modelcontextprotocol/inspector@2.11.0 --cli node dist/server.js --protocol-era modern --format json --method tools/call --tool-name greet --tool-arg name=Ada ``` Inspector starts the compiled server and sends this argument: ```json theme={null} { "name": "Ada" } ``` The successful result includes structured data and a text serialization: ```json theme={null} { "message": "Hello, Ada!" } ``` Try invalid input to see validation feedback. The handler does not run for an empty name: ```bash theme={null} npx --yes @modelcontextprotocol/inspector@2.11.0 --cli node dist/server.js --protocol-era modern --format json --method tools/call --tool-name greet --tool-args-json '{"name":""}' ``` > **Keep stdout clean.** MCP owns stdout. Send application diagnostics to stderr with `console.error()` rather than `console.log()`. ## Next steps [Configure a client](/getting-started/clients), [run the same tool over HTTP](/getting-started/http), or learn about [tool definitions](/tools/definitions). The complete runnable teaching example is in [apps/stdio-example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/stdio-example). # HTTP authorization Source: https://toolgrain.mintlify.app/guides/authorization Detailed HTTP authorization, public resource URLs, routing, and custom providers. Configure authorization on `createServer({ auth })`. Tools remain standalone and read the verified identity using their integration's synchronous `useAuth(ctx)`. The API is the same for MCP `2026-07-28` and `2025-06-18`. ## JWT ```ts theme={null} // tools/who-am-i.ts import { useAuth } from "@toolgrain/jwt"; import { tool } from "@toolgrain/mcp"; import { z } from "zod"; export const whoAmI = tool({ input: z.object({}), execute(_input, ctx) { const { claims } = useAuth(ctx); return { subject: claims.sub ?? null, issuer: claims.iss, expiresAt: claims.exp, }; }, }); ``` ```ts theme={null} // server.ts import { jwt } from "@toolgrain/jwt"; import { createServer } from "@toolgrain/mcp"; import { whoAmI } from "./tools/who-am-i.js"; export const server = createServer({ name: "jwt-example", version: "1.0.0", auth: jwt({ issuer: process.env.JWT_ISSUER! }), tools: { whoAmI }, }); ``` `JWT_ISSUER` is an application-defined environment variable containing your authorization provider's exact issuer identifier. Toolgrain discovers `jwks_uri` through OAuth authorization server metadata or OpenID Connect discovery, checking that the document's issuer matches the configured issuer. Path issuers use the standard discovery URL variants. `jwksUrl` is an optional explicit override for issuers without discovery. Metadata retrieval is bounded by size and time and does not follow redirects. Verification uses `jose`, with cached discovery and remote signing keys, including key rotation. The defaults allow RS256 and ES256. Override `algorithms` with supported asymmetric algorithms; symmetric algorithms and `none` are rejected. Tokens require a valid signature, the configured issuer, a matching resource audience, and `exp`. Expiration and any `nbf` are checked. Standard claim types are checked before exposure. Audience arrays contain only strings; `exp`, `iat`, and `nbf` must be finite numbers when present. Unsupported JWT critical headers are invalid tokens (401); signing-key retrieval/import failures remain provider errors (503). `iss`, `aud`, and `exp` are required; `sub`, `iat`, `nbf`, and `jti` are optional. Other claims have type `unknown`. JWT verification does not issue tokens or implement login, consent, OAuth client registration, or an authorization server. Use an OAuth provider supporting your MCP clients' authorization and registration flows. ## Clerk ```ts theme={null} // tools/who-am-i.ts import { useAuth } from "@toolgrain/clerk"; import { tool } from "@toolgrain/mcp"; import { z } from "zod"; export const whoAmI = tool({ input: z.object({}), execute(_input, ctx) { const auth = useAuth(ctx); return { userId: auth.userId, // string clientId: auth.clientId, // string scopes: auth.scopes, // readonly string[] }; }, }); ``` ```ts theme={null} // server.ts import { clerk } from "@toolgrain/clerk"; import { createServer } from "@toolgrain/mcp"; import { whoAmI } from "./tools/who-am-i.js"; export const server = createServer({ name: "clerk-example", version: "1.0.0", auth: clerk({ publishableKey: process.env.CLERK_PUBLISHABLE_KEY!, secretKey: process.env.CLERK_SECRET_KEY!, scopesSupported: ["openid", "profile", "email", "offline_access"], }), tools: { whoAmI }, }); ``` Get both keys from the same Clerk application/environment's API keys page. No `CLERK_ISSUER` variable is needed: the publishable key identifies the Frontend API and its issuer. Configure OAuth applications and client onboarding in Clerk for the MCP clients you intend to support. See [Clerk's OAuth guide](https://clerk.com/docs/guides/configure/auth-strategies/oauth/how-clerk-implements-oauth). For a runnable framework application and Inspector OAuth setup, see the [Elysia Clerk example](https://github.com/keshavkatwe/toolgrain/blob/main/apps/elysia-example/README.md#clerk-authorization-and-inspector). Enable `aud_claim_enabled` in Clerk's instance OAuth application settings. Clerk then includes the requested OAuth `resource` in access tokens' audience. Both JWT and opaque tokens must include the resolved MCP resource as their audience. Otherwise token exchange can succeed while MCP requests return `401 invalid_token`. Authorize again after enabling it to obtain a new token; existing tokens do not acquire the missing audience. Only OAuth access tokens for your resource are accepted. JWT OAuth tokens are verified against the Clerk issuer's signing keys; opaque `oat_` tokens are verified with Clerk's backend SDK and checked for audience, revocation, and expiration. Session tokens, API keys, and M2M tokens are rejected. The context contains plain identity data; credentials and SDK token-getter methods are not exposed. Scopes are available to application code but Toolgrain v0 does not implement per-tool scope policies. ## Standalone Node HTTP `http()` from `@toolgrain/node` owns the HTTP listener, routing, host validation, and shutdown. It works with both public and auth-configured servers: ```ts theme={null} import { http } from "@toolgrain/node"; import { server } from "./server.js"; const transport = http({ port: 3007, path: "/mcp" }); await server.listen(transport); console.log(transport.address()); // Your application decides when to stop, including process signal handling. // await server.close(); ``` The default bind hostname is `127.0.0.1`, port is `3000`, and endpoint path is `/mcp`. Port `0` requests an available port; `transport.address()` returns a copied Node address after startup and undefined before startup or after shutdown. Default accepted hosts are `localhost`, `127.0.0.1`, and `[::1]` on the actual listening port. `hostname` controls the bind address; `allowedHosts` separately controls accepted request authorities. Closing the server aborts active requests and verification, stops the listener, and closes its connections. Startup failures release the listener too. `server.listen()` claims each transport instance for its first server; that instance can be attached only once. Rejected reuse leaves the owning server running and the other server free to attach a fresh transport. Ownership is shared across compatible package copies and supports frozen custom transports. The transport does not install global process handlers. When auth is configured, Toolgrain automatically serves public GET/HEAD metadata at `/.well-known/oauth-protected-resource/mcp`. Custom paths, root paths, and significant trailing slashes produce their corresponding metadata paths. An explicit provider `resource` determines the advertised public metadata path. Unmatched routes return 404; a server without auth exposes no resource metadata. ## Combined handlers for existing applications `createHttpHandler(server, options?)` returns `(request: Request) => Promise` and includes the same MCP routing, public metadata, host validation, and authentication. Mount it at the application root so that both the endpoint and well-known metadata path reach it. A framework mount that strips `/mcp` from the Request URL is unsuitable for this combined handler. The returned `HttpHandler` also provides `matches(pathname)` for framework middleware to identify the MCP and configured metadata paths before consuming the request body. A Hono middleware can call `handler.matches(c.req.path) ? handler(c.req.raw) : next()`. For example, Elysia on Bun can mount the handler without consuming the body: ```ts theme={null} import { createHttpHandler } from "@toolgrain/http"; import { Elysia } from "elysia"; import { server } from "./server.js"; const handler = createHttpHandler(server, { path: "/mcp", allowedHosts: ["localhost:3003", "127.0.0.1:3003"], }); new Elysia() .get("/health", () => ({ status: "ok" })) .mount(handler) .onStop(() => server.close()) .listen({ hostname: "127.0.0.1", port: 3003 }); ``` `createNodeHttpHandler(server, options?)` from `@toolgrain/node` provides the same combined handler for Node IncomingMessage/ServerResponse. Mount it at the root before body parsing middleware. When Express supplies `next`, unmatched paths are delegated immediately, with their request bodies untouched. Matched MCP requests keep their authentication, protocol, and error responses, including 404 protocol errors. Without a middleware continuation, unmatched paths return 404. These handler factories leave listener ownership with the application. Separate `createProtectedResourceMetadataHandler(server, { allowedHosts? })` and `createNodeProtectedResourceMetadataHandler(server, { allowedHosts? })` remain available for frameworks that require explicit filesystem or route registration. They apply host validation too; the hosting platform must route the public well-known path to them. ## Host validation and resource inference Handlers accept `path`, `allowedHosts`, `allowedOrigins`, and `maxMessageBytes`. Paths default to `/mcp` and must be absolute URL paths without query strings, fragments, whitespace, or dot-segment normalization. `allowedHosts` contains exact hostnames or IP addresses, optionally with ports, for example `["api.example.com", "[::1]:3003"]`. Matching normalizes case and standard URL ports; wildcards, schemes, and paths are rejected. An empty list rejects every host. Configured arrays are copied. Both the request URL authority and any supplied Host header must be allowed. When a framework normalizes the URL host (for example Next.js using localhost for loopback), the validated Host header preserves the actual resource authority. Disallowed hosts receive 403 before routing, authentication, or body parsing, including on metadata requests. Standalone `http()` derives exact local authorities from the listening port. Existing-application handlers default to the three loopback hostnames on any port because they do not own the listener. Set `allowedHosts` for production or to restrict development to a particular port. `allowedOrigins` separately checks the browser Origin header on MCP requests; it is not a host allowlist or a CORS implementation. For `https://api.example.com/mcp`, the inferred resource is `https://api.example.com/mcp`. Query parameters are excluded. Paths and significant trailing slashes are preserved; a root resource uses the origin without `/`. Metadata works before any authenticated request; no first-request origin is cached. Metadata, challenges, and token audience verification use the same resource. Applications still supply deployment configuration and trusted proxy normalization. Node uses the actual Host, target, port, and direct TLS scheme and ignores Forwarded and X-Forwarded-\* headers. If a trusted proxy rewrites the external scheme, host, or path, supply a normalized public Web Request (including its Host header), or configure a canonical provider resource: ```ts theme={null} clerk({ publishableKey, secretKey, resource: "https://api.example.com/mcp", }); ``` The JWT adapter accepts the same optional `resource` override. Configure `allowedHosts` for the authorities that reach the handler; a resource override does not disable host validation. Auth URLs require HTTPS, with HTTP loopback exceptions for development. Configured auth URLs reject credentials, queries, fragments, and whitespace. Applications continue to own TLS, CORS, and any framework listener. The [JWT example](https://github.com/keshavkatwe/toolgrain/blob/main/apps/jwt-example/README.md) demonstrates managed Node HTTP and both protocol revisions. ## Request behavior After endpoint checks, authentication runs before body parsing or tool work. Credentials must be a bearer token in the `Authorization` header. Query tokens are rejected; cookies, request `_meta`, and tool arguments do not establish an identity. Each authenticated request gets its own copied, deeply frozen identity. Calling another integration's `useAuth` or using a context without auth throws. | Condition | HTTP status | | - | - | | Missing or invalid/expired access token | 401, with a resource metadata challenge | | Malformed bearer credentials or a query token | 400 | | Provider access denial | 403 | | Verified token lacks an application-required scope | 403, `insufficient_scope` challenge | | Provider/network failure or closed server | 503 | These HTTP statuses are the same in both protocol eras. JWT and Clerk audience failures include an actionable `error_description` in the JSON body and the `WWW-Authenticate` challenge. Missing `aud` and an audience that does not match the resource have distinct messages. For example: ```json theme={null} { "error": "invalid_token", "error_description": "Access token is missing the aud claim. Configure the authorization server to include an audience and request a new token with resource=http://127.0.0.1:3007/mcp." } ``` A mismatch reports the expected resource and asks the client to request a new token for it. These descriptions include only the expected resource, never the received token, its actual audience, or other claims. Signature verification or Clerk backend verification runs before audience diagnostics; invalid credentials and private provider errors retain generic responses. Raw error messages and causes are never automatically exposed. Challenge descriptions use Bearer-safe ASCII; the JSON body preserves the readable description. Unexpected verification failures, including provider `AuthError("temporarily_unavailable")` outages, reach the server's `onError(error)` callback once with the original thrown value and its private cause, if present. No tool/request details or credentials are added. Expected auth rejections (`invalid_request`, `invalid_token`, `access_denied`, and `insufficient_scope`), closed-server rejections, and failures after cancellation do not reach the callback. Callback throws and asynchronous rejections cannot disrupt the response or cleanup. Public metadata uses `Cache-Control: no-store` and is available without a bearer token. Verification, body reading, and execution share request cancellation and server shutdown. The server stops waiting if verification cannot be cancelled by the integration. Shared JWT discovery/key fetches may finish for other requests; Clerk's backend SDK may finish its in-flight request. Late identities and handler results are discarded. Tool execution remains cooperatively cancellable. An auth-configured server accepts request transports such as `http()` and rejects message transports such as `stdio()` before startup. This authorization API is HTTP-only; stdio servers use their process/environment trust model. ## Resource scopes Set `scopesSupported` on `clerk()`, `jwt()`, or a custom `AuthProvider` to declare this resource's intended scope catalog. The HTTP handlers include the exact list as `scopes_supported` in canonical public protected-resource discovery, for example `/.well-known/oauth-protected-resource/mcp`. No response wrapper is needed. Resource scopes let clients choose from this catalog instead of falling back to the authorization server's potentially broader list. Client scope selection is owned by the client; Toolgrain does not run the authorization request. Omission leaves the field absent, preserving existing behavior. An explicit `[]` declares no supported scopes. Arrays preserve order and case, are copied, and must contain unique, nonempty RFC 6749 scope tokens: ASCII without whitespace, double quotes, or backslashes. Invalid configuration throws `TypeError` at integration or server construction. Host validation, public GET/HEAD discovery, token verification, and audience checks still apply. Supported scopes are separate from required scopes. Applications own scope policy. For a server-wide policy, verify the token first, then check its granted scopes in a provider wrapper: ```ts theme={null} import { clerk } from "@toolgrain/clerk"; import { AuthError } from "@toolgrain/mcp"; const provider = clerk({ publishableKey: process.env.CLERK_PUBLISHABLE_KEY!, secretKey: process.env.CLERK_SECRET_KEY!, scopesSupported: ["openid", "profile", "email", "offline_access"], }); const auth: typeof provider = { ...provider, async verify(token, options) { const identity = await provider.verify(token, options); if (!identity.scopes.includes("profile")) { throw new AuthError("insufficient_scope", { requiredScopes: ["profile"], description: "Reauthorize this connection with the profile scope.", }); } return identity; }, }; // Pass auth to createServer({ auth, ... }). ``` A verifier's genuine scope denial becomes HTTP 403 with a Bearer challenge: ```http theme={null} WWW-Authenticate: Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp", error="insufficient_scope", error_description="Reauthorize this connection with the profile scope.", scope="profile" ``` `requiredScopes` is an optional copied, frozen list. Omission or `[]` omits `scope` from the challenge. The response body contains the error code and an explicitly supplied public description; private causes stay private. A generic provider 403 remains `access_denied`; it is not evidence of insufficient scope. This mapping applies to authorization before body parsing. Per-tool permissions remain application policy, and throwing from a tool follows the existing tool error contract rather than creating an HTTP auth challenge. ### Troubleshoot scope failures | Observation | Check and action | | - | - | | Resource metadata has no `scopes_supported` | Declare `scopesSupported`; inspect the canonical metadata URL using the public host. A client may otherwise use the authorization server's full scope catalog. | | Authorization redirect reports `invalid_scope` | Compare the scope names requested by the client with both the resource catalog and the authorization server's allowed scopes. Correct the configuration and authorize again. This redirect happens at the authorization server, outside Toolgrain's HTTP handler. | | Resource returns `403 insufficient_scope` | Token verification succeeded but application policy requires additional scopes. Check the challenge's optional `scope`, ensure the provider allows them, and reauthorize. A refresh alone may not expand the grant. | Scope names and failure categories are useful diagnostics. Do not log bearer or refresh tokens, secrets, raw provider responses, or profile data. Declare only the scopes the resource needs; do not copy the provider's entire scope catalog. For live acceptance, connect a client that chooses scopes from discovery while the authorization server advertises additional scopes. Check the authorization request and consent screen, then verify tool access. Repeat fresh authorization with CIMD and DCR clients and verify refresh/retry. These client/provider flows require your configuration and credentials; local metadata and offline token tests do not establish live OAuth interoperability. ### Live scope acceptance On **November 8, 2026**, a self-authored acceptance client using `@modelcontextprotocol/client` **2.3.1** on Node **24.22.2** completed real OAuth flows against a Clerk development instance. The Elysia **1.4.30** server ran on Bun **1.4.4**, using published Toolgrain **0.3.0** packages and independent HTTP POSTs on loopback. Consent used Chrome **156.0.8078.81**. The server's direct `clerk()` configuration declared `scopesSupported`; the native HTTP handler served discovery without a metadata-response wrapper. | Check | CIMD | DCR | | - | - | - | | Fresh client with no saved registration or tokens | HTTPS client metadata document | New dynamic registration | | Authorization code, S256 PKCE, state and issuer binding | Passed | Passed | | Native canonical metadata GET/HEAD | Passed | Passed | | Automatic resource scope selection and consent | Passed | Passed | | Initial and refreshed tool access in both MCP revisions | Passed | Passed | | Refresh, then retry after a deliberate invalid-token 401 | Passed | Passed | The client supplied no scope override. It selected exactly `openid profile email offline_access` from resource discovery, even though Clerk advertised additional `public_metadata` and `private_metadata` scopes. Both consent screens requested identity, basic profile, and email access. The issued grants retained exactly the declared scopes and the requested MCP resource audience. `greet` and `whoAmI` calls passed before and after refresh in MCP `2026-07-28` and `2025-06-18`; verified identity values stayed out of the record. Each 401 recovery performed another real refresh and a successful retry. Both clients' access and refresh tokens were revoked after verification. The disposable DCR registration was removed, and the local services and temporary public CIMD metadata endpoint were stopped. Clerk instance settings were unchanged. This records the tested development instance and acceptance client. Production Clerk configurations, packaged client UIs such as Claude Desktop or Claude Code, remote MCP endpoints, and expiry-driven refresh remain outside this test. ## Custom providers and direct invocation Integrations implement `AuthProvider` from `@toolgrain/mcp`, with a registered provider `type` symbol, optional canonical `resource`, nonempty `authorizationServers`, optional `scopesSupported`, and `verify(token, { resource, signal })`. Return plain identity data and throw `AuthError` with `invalid_token`, `access_denied`, `insufficient_scope`, or `temporarily_unavailable` as appropriate. `createAuthAccessor(type)` creates a typed accessor returning recursively readonly identity data. Matching compatible package copies share provider/context symbols. Custom providers can use `validateTokenAudience(verifiedAudience, resource)` from `@toolgrain/mcp` after verifying a token's authenticity and validity. It accepts a string or array of strings, requires a match for the expected resource, and throws `AuthError` with public guidance for missing or mismatched audiences. It does not verify signatures, issuers, expiration, or revocation itself. `new AuthError(code, { description, cause })` allows an explicitly public description separate from a private cause. `description` also becomes the error's message and is included as `error_description` by HTTP adapters. Include only information intended for clients; never copy raw provider errors or credentials into it. Omitting `description` preserves the existing generic response. The HTTP adapters call `server.authorize(token, { resource, signal? })`, then pass the opaque scope to `server.handle(message, { auth: scope, protocolVersion? })`. Custom transport integrations must dispose the scope in `finally`. Scopes are single-use, server-bound, and cannot be fabricated or reused after disposal. Calling `handle` without a valid scope on a protected server is rejected. `getAuthMetadata()` returns copied configuration for HTTP adapters. `toolContext()` creates an unauthenticated context. Directly calling a tool's raw `execute` bypasses server authorization and validation; test protected execution through `authorize` and `handle` instead. [Lazy context providers](/guides/context) can read `useAuth(ctx)` and depend on other providers through inferred async accessors. Authorization is still eagerly verified before context resolution; synchronous `useAuth(ctx)` does no work. # Cancellation and execution deadlines Source: https://toolgrain.mintlify.app/guides/cancellation Observe request cancellation and set application operation deadlines. Cancellation is cooperative. Toolgrain aborts `ctx.signal`, prevents a handler from starting after cancelled input validation, and suppresses late responses. Application work stops only if it observes the signal. ```ts theme={null} import { tool } from "@toolgrain/mcp"; import { z } from "zod"; const readRemote = tool({ input: z.object({ path: z.string() }), async execute({ path }, ctx) { const response = await fetch(new URL(path, "https://api.example.com"), { signal: ctx.signal, }); return response.text(); }, }); ``` For real applications, validate any caller-controlled paths and constrain the destinations the tool may access. The example demonstrates cancellation, not a general remote-fetch service. ## When the signal aborts * A stdio `notifications/cancelled` message cancels the matching request. * HTTP caller/disconnect signals propagate through `handle()` and the adapters. * Transport close, stdin EOF, and server close abort active work. * A `handle()` caller may pass its own `AbortSignal`. * A direct handler's progress-delivery callback failure cancels that invocation with `AbortError` reason `Progress delivery failed` and one-argument transport diagnostics. Signals use `AbortError` reasons for Toolgrain-owned cancellation: client cancellation, connection close, or server close. A caller's own `handle()` abort reason is otherwise preserved. Inspect `ctx.signal.reason` if your application needs the distinction. Cancelled late failures do not trigger diagnostics. A handler that ignores cancellation can still consume resources; on stdio its request ID remains reserved until it settles. ## Set an application deadline ```ts theme={null} async execute(input, ctx) { const signal = AbortSignal.any([ ctx.signal, AbortSignal.timeout(10_000), ]); return applicationService.read(input, { signal }); } ``` Here `applicationService` is your application operation, which must actually honor the signal. A timeout rejection becomes an unexpected tool failure unless your handler intentionally converts it into safe public feedback. Do not merely race a promise and assume the underlying operation has stopped. Client timeouts are not guaranteed to send cancellation or disconnect promptly. The [interoperability report](/compatibility/clients) reproduces this in the tested Codex direct-call API. Toolgrain has no built-in per-tool timeout setting. Legacy HTTP cancellation notifications are advisory in the independent-request design; they do not introduce a session-wide request map. HTTP disconnects still abort the affected handler. Do not infer cancellation behavior from the arrival of a notification alone. # Lazy context providers Source: https://toolgrain.mintlify.app/guides/context Resolve typed application services lazily, with request caching and test overrides. Define reusable providers with `createContext()` from `@toolgrain/mcp`. Export `provider.use` under an application-specific name such as `useDatabase`. Toolgrain infers the returned value from the resolver, including asynchronous resolvers; no explicit context type arguments or generic `ToolContext` are needed. ## Define providers and standalone tools ```ts theme={null} import { createContext, createServer, tool } from "@toolgrain/mcp"; import { stdio } from "@toolgrain/node"; import { z } from "zod"; // An application-owned database client or pool. Replace this with your client. const sharedDatabase = { async findUser(id: string, signal: AbortSignal) { signal.throwIfAborted(); return { id, name: "Ada" }; }, }; export const database = createContext({ name: "database", resolve: () => sharedDatabase, }); export const useDatabase = database.use; export const services = createContext({ name: "services", async resolve(ctx) { const db = await useDatabase(ctx); return { findUser: (id: string) => db.findUser(id, ctx.signal), }; }, }); export const useServices = services.use; export const findUser = tool({ input: z.object({ id: z.string() }), async execute({ id }, ctx) { const services = await useServices(ctx); return services.findUser(id); }, }); const server = createServer({ name: "users", version: "1.0.0", tools: { findUser }, context: [services, database], }); await server.listen(stdio()); ``` The registration order does not matter. Calling `useServices(ctx)` starts its resolver, which calls `useDatabase(ctx)` to resolve its dependency. Both providers must be registered explicitly; accessor calls do not register dependencies. The same providers work with HTTP and both supported MCP revisions. ## Resolution and request caching Every accessor returns a `Promise`, even when its resolver is synchronous. Resolve dependencies inside the resolver and await their accessors. Returned service methods can then use those resolved dependencies. Accessors should be awaited within the active handler or resolver, rather than used for background work. Factories run on first access, after authorization and tool input validation. Discovery, tool listing, unknown tools, invalid input, and unused registrations never start factories. A context caches one promise per provider: concurrent readers share the same in-flight work and receive the same value. Failures are cached too; a later access in that context does not retry the factory. A fresh request gets a fresh cache, even if the request ID matches another request. Provider names must be nonempty strings and label diagnostic messages. Identity belongs to the definition, so two independently created providers with the same name are distinct. Registering the same identity twice, including its overrides, is a construction error. Definitions and registration snapshots are immutable. Providers from compatible installed copies of `@toolgrain/mcp` interoperate. Context values may contain functions, class instances, and mutable database clients. They are returned unchanged, without copying or freezing. Request caching does not make an existing shared pool request-owned: if the resolver returns a shared client, requests intentionally receive that client. Applications own creation and disposal of resources; this version adds no cleanup hooks, transactions, or automatic pool/connection closing. ## Typed overrides and direct tests `.provide(resolver)` creates a new binding with the original provider's identity and value type. Existing accessors find that binding without changing the original provider, another server, or another context. Both sync and async overrides are supported and must return the complete inferred contract. ```ts theme={null} import { toolContext } from "@toolgrain/mcp"; const fakeDatabase = { async findUser(id: string, signal: AbortSignal) { signal.throwIfAborted(); return { id, name: "Test user" }; }, }; const ctx = toolContext({ context: [services, database.provide(() => fakeDatabase)], }); const user = await findUser.execute({ id: "user_1" }, ctx); ``` Use the same override in a server's `context` array for per-server configuration. Register the override instead of the original provider. `toolContext()` defaults to no providers, with a fresh cache each time; reusing one context reuses its cache. Direct `execute()` calls remain raw calls: they bypass server authorization, argument/output validation, and MCP conversion. Test protected execution through `authorize()` and `handle()` as described in the [authorization guide](/guides/authorization). ## Authorization and cancellation A resolver receives `ToolContext` with the same request data, `AbortSignal`, and verified identity as the tool. Authorization remains eager and independent of lazy context resolution. Integration-specific `useAuth(ctx)` stays synchronous: ```ts theme={null} import { useAuth } from "@toolgrain/clerk"; const account = createContext({ name: "account", async resolve(ctx) { const { userId } = useAuth(ctx); const db = await useDatabase(ctx); return db.findUser(userId, ctx.signal); }, }); ``` Configure Clerk on the server and register `account` and `database`. The frozen auth snapshot remains available through nested provider calls. Stdio still has no HTTP authorization identity. Accessors check cancellation before access, before factory startup, and after resolution. Pass `ctx.signal` to cancellable work. Cancellation remains cooperative: a factory ignoring the signal can keep running until it settles, but its late value is not delivered and the cancelled request sends no response. Existing client cancellation, disconnect, transport close, and server close behavior applies to providers too. ## Errors and type safety A missing registration rejects when accessed, naming the missing provider. Cycles among pending provider resolutions reject with a diagnostic chain such as `Context dependency cycle: services -> database -> services`. Concurrent readers and shared dependency diamonds are valid. Direct accessors reject with the original error. During server execution, missing providers, cycles, and resolver exceptions produce generic `Tool execution failed` tool results. The original errors and frozen tool/request details reach `onError(error, details)`; see [errors and diagnostics](/tools/overview#errors-and-diagnostics). No new HTTP authorization status is added. TypeScript infers accessor results and checks overrides. It cannot prove a standalone tool's dynamically accessed providers are registered on every server; missing registrations and cycles are runtime errors. Construct contexts with `toolContext()` rather than hand-written objects. # Run a server in production Source: https://toolgrain.mintlify.app/guides/production Plan public URLs, permissions, limits, cancellation, and shutdown. Toolgrain owns the MCP boundary. Your application owns deployment, application permissions, resource lifecycle, and the infrastructure around the listener. Start with a real client call and a cancellation/disconnect check in your target environment. ## Public URLs and trusted proxies Configure exact `allowedHosts` authorities. Binding an HTTP listener to `0.0.0.0` does not authorize arbitrary Host values. If a proxy terminates TLS or changes request URLs, normalize the public URL through middleware that trusts only your known proxy. Node adapters preserve the direct scheme and request target and ignore forwarded headers. Audience checks and protected-resource metadata must use the public resource URL, including the MCP endpoint path and excluding queries. An explicit provider `resource` can override inference; it does not replace host validation. Make metadata GET/HEAD routes reachable through the same public infrastructure. ## Authorization and application permissions Use endpoint authorization for tools that require authenticated callers. Grant the application service only the permissions its tools need. Enforce action-specific user/scope policies in application code; successful token verification does not automatically permit every tool action. Keep secret keys server-side and accept credentials through Bearer headers, not query strings. Client capability/info fields and arbitrary request metadata are self-reported. Treat them as untrusted even though Toolgrain freezes their copies. ## CORS and request limits `allowedOrigins` checks a supplied Origin. It does not implement CORS responses or preflight handling. Configure browser access in your framework if required. Put the MCP handler before body parsing. Keep the incoming message limit appropriate for your tools; adapters default to 1 MiB. Application listeners/proxies own connection limits, rate limiting, TLS, and additional infrastructure timeouts. ## Deadlines and cancellation Pass `ctx.signal` to application operations and set explicit operation deadlines where needed. A client timeout may not promptly cancel server work. A handler/provider that ignores a signal can keep running after the response has been discarded. Do not assume a raced promise or a closed connection has stopped a database query. ## Shutdown and resource ownership For the managed Node transport, `server.close()` stops its listener. For framework adapters, close the framework listener and Toolgrain server. Close application-owned pools and clients yourself after coordinating outstanding work. Context providers do not automatically dispose values or open transactions. Close is terminal, idempotent, and re-entrant. Do not try to restart an attached transport; construct a fresh server/transport for a new lifecycle. ## Diagnostics and deployment checks Keep protocol stdout clean on stdio. Record unexpected errors with `onError`, keeping raw failures in private diagnostics. Review logging of client metadata and application data. Verify discovery, listing, a successful call, invalid input, auth rejection, metadata discovery, disconnects, and shutdown on your actual runtime. Use the [support policy](/project/support-policy) and [interoperability report](/compatibility/clients) to distinguish a supported target from a verified combination. Toolgrain supplies request-scoped SSE progress; sessions, resumability, and subscriptions remain outside the current scope. Configure reverse proxies and framework response handling to pass streaming bodies through promptly. Dated client reports do not verify progress UI presentation. # Request context Source: https://toolgrain.mintlify.app/guides/request-context Read request metadata, observe cancellation, and report progress from tool handlers. Handlers receive a second argument, `ctx: ToolContext`. Use it for cancellation, progress, and request information without making the tool definition specific to a server or auth provider. ```ts theme={null} import { tool } from "@toolgrain/mcp"; import { z } from "zod"; const lookup = tool({ input: z.object({ id: z.string() }), async execute({ id }, ctx) { ctx.signal.throwIfAborted(); console.error("lookup", ctx.request.id); return { id }; }, }); ``` ## Fields | Field | Meaning | | - | - | | `signal` | AbortSignal for the active request | | `reportProgress(update)` | Bound asynchronous progress reporter; no-op without a client token or delivery channel | | `request.id` | JSON-RPC request ID | | `request.protocolVersion` | Selected supported revision | | `request.client` | Optional self-reported client info and capabilities | | `request.meta` | Deeply frozen copy of request `_meta`, empty when absent | `request`, its metadata, and any client details are frozen per-request copies. Changing data in one request cannot mutate another request's snapshot. Client details are unverified and are absent where the transport and era provide none, such as legacy HTTP. Never use a client name or capability declaration as an authenticated identity. Client info/capabilities use a readonly union of modern and legacy wire types. `ToolRequest` is not a discriminated union: checking `protocolVersion` does not narrow the client type. Guard fields that differ between eras. ## Application data Use [context providers](/guides/context) for services such as database access, and integration-specific [auth accessors](/authentication/overview) for verified identity. `ToolContext` itself remains non-generic. Provider accessors return promises; JWT and Clerk `useAuth(ctx)` accessors remain synchronous. ## Constructing a context for tests ```ts theme={null} import { toolContext } from "@toolgrain/mcp"; const ctx = toolContext({ request: { id: "test-1", meta: { source: "test" } } }); const value = await lookup.execute({ id: "u_1" }, ctx); ``` The helper defaults omitted fields independently: ID `0`, the modern revision, no client, empty metadata, a fresh signal, and no registered providers. Reusing one context reuses its provider cache. Use the helper rather than hand-building context objects; future fields may be supplied by the helper. Direct calls bypass server validation and authorization. ## Report progress Tool handlers and context providers can report progress during an active invocation: ```ts theme={null} const processFiles = tool({ input: z.object({ files: z.array(z.string()) }), async execute({ files }, ctx) { for (let index = 0; index < files.length; index++) { ctx.signal.throwIfAborted(); // Perform application work for files[index], observing ctx.signal. await ctx.reportProgress({ progress: index + 1, total: files.length, message: `Processed ${index + 1} files`, }); } return { processed: files.length }; }, }); ``` The MCP client opts in with a string or integer `params._meta.progressToken`. Toolgrain attaches that token to `notifications/progress`. Without a token or delivery channel, reports resolve without sending. `toolContext()` uses that no-op behavior for direct calls. Tool results retain their normal validation and conversion. Clients must choose unique tokens for active requests. On a shared message connection, Toolgrain rejects a duplicate active token with `-32602` before invoking the handler. String and integer tokens are distinct. Completion or cancellation releases the token for reuse; independent HTTP response streams keep their tokens isolated. Progress values must be finite and strictly increase. `total` and `message` are optional; values may be fractional. Await reports to respect backpressure and use `ctx.signal` to stop application work on cancellation. Reports after completion or cancellation send nothing. The bound method can be passed as `reportProgress: ctx.reportProgress` to application helpers alongside `ctx.signal`. The first update is sent immediately. Later updates are spaced at least 100 ms apart per invocation, also respecting delivery backpressure. Accepted updates retain their order and finish before the final response; they are not dropped. Await each report to avoid building up a queue. Cancellation and shutdown clear pending pacing timers and suppress queued updates. This is a per-request limit, not a server-wide connection or request limit. Stdio uses its existing message channel. HTTP opens a POST SSE response on the first progress update, sends the final response on the same stream, and ends it. Calls that send no updates retain JSON responses. Progress belongs to the individual request and does not require `subscriptions/listen`. Client UI presentation is separate from protocol delivery; the dated client compatibility reports do not verify progress displays. # Serve resources Source: https://toolgrain.mintlify.app/guides/resources Declare reusable fixed-URI resources and read text or binary content through MCP. Resources expose content that clients can discover and read separately from tool calls. Declare a fixed URI with `resource()` and register its definition beside your tools. Toolgrain never fetches URLs or maps URIs to local files automatically. ## Declare and register a resource ```ts theme={null} import { createServer, resource } from "@toolgrain/mcp"; import { stdio } from "@toolgrain/node"; const guide = resource({ uri: "docs://getting-started", name: "getting-started", title: "Getting started", mimeType: "text/markdown", read: (uri) => ({ contents: [{ uri, mimeType: "text/markdown", text: "# Getting started\n\nWelcome to this server.", }], }), }); const server = createServer({ name: "documentation", version: "1.0.0", tools: {}, resources: [guide], }); await server.listen(stdio()); ``` The URI belongs to the frozen definition. Reuse it across servers or pass a modified spread back through `resource()` to create another definition. Raw objects and spreads are not valid registrations. Duplicate URIs fail server construction. Readonly registration arrays and content arrays are accepted. Registration copies display metadata without invoking readers. `resources/list` returns this fixed list in registration order. `resources/read` matches URI strings exactly and invokes the matching reader. Custom schemes, including `ui://` and `urn:`, are accepted when they form valid absolute URIs. ## Return explicit contents A reader returns `{ contents, _meta? }`, synchronously or asynchronously. Every entry supplies its own URI, optional MIME type and `_meta`, and exactly one of `text` or base64 `blob`. One read can return several entries. Listing metadata is not automatically copied onto content entries. ```ts theme={null} const report = resource({ uri: "reports://latest", name: "latest-report", read: (uri) => ({ contents: [ { uri, mimeType: "text/plain", text: "Report complete." }, { uri: "reports://latest/data", mimeType: "application/octet-stream", blob: "YQ==" }, ], _meta: { "example.com/report-version": 1 }, }), }); ``` Toolgrain validates and copies results. Non-JSON values, malformed base64, invalid URIs, missing payloads, and entries containing both text and blob fail privately. Undefined optional object properties are omitted. An existing resource may return `contents: []`; an unknown URI returns a resource-not-found error instead. ## Use context and authorization `read(uri, ctx)` receives the existing `ToolContext`: frozen request/client metadata, `ctx.signal`, auth accessors, and [lazy context providers](/guides/context). Providers resolve only on access and cache per read request. Readers own their application services and should pass `ctx.signal` to cancellable work. Configured endpoint authentication runs before resource work. The static list is the same for every authorized caller; resource-specific authorization policies and dynamic discovery are not provided. Readers can use the verified identity through JWT/Clerk's `useAuth(ctx)` when producing content. For direct calls in tests, use `guide.read(guide.uri, toolContext())` after importing `toolContext` from `@toolgrain/mcp`. Direct reads remain raw: they bypass endpoint auth and result validation. Context provider overrides work through `toolContext()`. ## Protocol behavior and limits Both MCP `2026-07-28` and `2025-06-18` support listing and reading over the existing transports. Modern HTTP reads require `Mcp-Method: resources/read` and a `Mcp-Name` header matching the URI, plus the usual request metadata and version header. See [HTTP transport](/transports/http) for header encoding and hosting requirements. Supplying `resources`, even `[]`, advertises `resources: {}`. Omitting it leaves resource methods disabled. `resources/list` pages through the static registration snapshot in registration order, with at most `listPageSize` entries (default `100`). Pass each response's `nextCursor` as the next request's `cursor` until `nextCursor` is absent. Invalid cursors return `-32602`. See [list pagination](/reference/mcp#list-pagination) for cursor lifetime and configuration. `resources/templates/list` returns an empty list; template declarations, subscriptions, and list-change notifications are not supported. Modern resource results include `resultType: "complete"`, `ttlMs: 0`, and `cacheScope: "private"`. Legacy results omit those fields and listing icons. Unknown URIs return `Resource not found` with code `-32602` in modern mode or `-32002` in legacy mode. Unexpected reader/provider/output failures return `-32603` with `Internal error`; `onError(error)` receives the original failure. Cancelled requests suppress late results and diagnostics. Resource and content-item `_meta` are preserved, including UI security metadata. Use this resource foundation with the [native MCP Apps integration](/mcp-apps/overview). The host renders widgets; Toolgrain serves HTML and links tools through metadata. See the [resource API reference](/reference/resources), the runnable [Elysia example](https://github.com/keshavkatwe/toolgrain/tree/main/apps/elysia-example), and the [MCP resource specification](https://modelcontextprotocol.io/specification/2026-07-28/server/resources). # Test tools and server behavior Source: https://toolgrain.mintlify.app/guides/testing Test handler logic separately from validation, protocol, and transport behavior. Use direct calls for application logic and server calls for validation, result conversion, diagnostics, and authorization. A passing direct handler test does not establish the public MCP contract. ## Direct handler test ```ts theme={null} import assert from "node:assert/strict"; import { createServer, toolContext } from "@toolgrain/mcp"; import { greet } from "./tools/greet.js"; const result = await greet.execute({ name: "Ada" }, toolContext()); assert.deepEqual(result, { message: "Hello, Ada!" }); ``` Save this as `src/test.ts` in the [modular tutorial project](/getting-started/stdio). The next block continues the same file. Inputs here are already the handler's parsed values. Direct calls bypass parsing, output validation, authorization, and MCP conversion. ## Test the server boundary ```ts theme={null} const server = createServer({ name: "test", version: "1.0.0", tools: { greet } }); try { const response = await server.handle({ jsonrpc: "2.0", id: "test-1", method: "tools/call", params: { name: "greet", arguments: { name: "Ada" }, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}, }, }, }); assert.ok(response && "result" in response); assert.deepEqual(response.result.structuredContent, { message: "Hello, Ada!" }); } finally { await server.close(); } ``` Compile and run the test with `npx tsc -p tsconfig.json` and `node dist/test.js`. For your own tools, also assert text blocks, send invalid input and check that the handler is not invoked, and test output failures. Check that unexpected failures remain generic and reach private `onError` details. Use the actual legacy envelope when checking the older revision rather than only changing a version label. ## Override services Providers support typed replacements without mutating the original definition: ```ts theme={null} const ctx = toolContext({ context: [database.provide(() => fakeDatabase)], }); ``` Here `database` is your provider and `fakeDatabase` implements its inferred contract. Concurrent accessor calls should share one value per context; fresh contexts should not share request caches. The [context guide](/guides/context#typed-overrides-and-direct-tests) includes a complete example. ## Transport and auth tests Test stdio through a real child process to catch stdout pollution, framing, EOF, and cancellation. Test HTTP through its adapter/listener to cover hosts, headers, body limits, metadata routes, authorization ordering, and disconnects. `server.handle()` alone does not exercise those HTTP boundaries. For protected direct tests, obtain a scope with `authorize()`, pass it to `handle()`, and dispose it in `finally`. Stub trusted signing keys or token-verification responses rather than requiring live secrets in ordinary tests. Keep live login interoperability checks separate and record client/runtime versions. # Troubleshooting Source: https://toolgrain.mintlify.app/guides/troubleshooting Diagnose tool, transport, authorization, and client behavior. Start by recording the Toolgrain revision/version, client version, runtime, transport, negotiated protocol, and the smallest failing request. Inspector helps separate server behavior from a model's tool selection or a client's result presentation. ## The stdio server appears silent It may be waiting for protocol messages. Connect an MCP client rather than typing application arguments into stdin. Confirm the configured executable and compiled file exist, use absolute paths, and rebuild before reconnecting. Send logs to stderr; any ordinary text on stdout can corrupt framing. ## A tool is missing or server construction fails Register definitions created by `tool()`, not raw objects or spreads. Names come from registration keys. Check `ToolNameError` for naming rules and `ToolSchemaError.schemaKind` for input, output, or metadata conversion problems. Inputs need an object root and a representable JSON Schema. ## Invalid input or generic tool failure Ordinary input validation produces public feedback. A generic `Tool execution failed` points to an unexpected parsing, output, handler, or provider failure: inspect private `onError` diagnostics. Check missing provider registrations and cycles. With an output schema, successful rich results require structured content. Avoid undefined, bigint, cyclic data, and unsupported output values. ## HTTP 403, 404, or rejected headers Check the endpoint path, URL authority, Host header, and Origin separately. Match exact allowed authorities, including non-default ports when configured. Do not add wildcard hosts. Mount combined handlers at the root before body parsing; filesystem routers need a separate metadata route for protected endpoints. A GET on `/mcp` is not an SSE stream. ## Authentication rejects a token Use an OAuth access token for the expected public resource. Check issuer, audience, expiration, and signature algorithm. Clerk sessions/API keys/M2M tokens are intentionally rejected. Audience errors distinguish missing `aud` from mismatch and identify the expected resource; do not print or share the raw token to debug this. Provider outages are separate from invalid credentials. Unexpected auth errors reach `onError` without tool/request details. Read [authorization behavior](/guides/authorization#request-behavior). ## A timeout does not stop the handler Observe `ctx.signal`, test explicit cancellation/disconnects, and add an application deadline. The tested Codex direct-call path timed out without promptly cancelling server work. A handler that ignores the signal continues until it settles; late results are suppressed. ## Text disappears beside structured data The tested Claude Code version presented only structured content when both were supplied. Include essential narrative in structured data, or use text-only results without an output schema when that is the tool's contract. See the [client report](/compatibility/clients). ## Report a problem Open a [GitHub issue](https://github.com/keshavkatwe/toolgrain/issues) with a minimal reproduction and sanitized diagnostics. Include exact versions and whether the same request works in Inspector. Omit secrets, real access tokens, and private application data. # Introduction Source: https://toolgrain.mintlify.app/index Bring your TypeScript application to MCP with reusable, typed tools. Toolgrain is a TypeScript toolkit for building [Model Context Protocol](https://modelcontextprotocol.io/) servers. Define tools with Zod, compose them into a server, and connect them to your application's services over stdio or HTTP. > [card] [Build your first server](/quickstart) > > Install Toolgrain, define a tool, and make your first MCP call. > [card] [Explore the examples](/examples) > > Start from stdio, Node HTTP, Express, Hono, Elysia, or Next.js. ## Define a tool once Describe the input and output with Zod. Toolgrain infers your handler's types and validates values at runtime. ```ts theme={null} import { tool } from "@toolgrain/mcp"; import { z } from "zod"; const greet = tool({ description: "Greet someone by name", input: z.object({ name: z.string().min(1) }), output: z.object({ message: z.string() }), execute: ({ name }) => ({ message: `Hello, ${name}!` }), }); ``` Register `greet` with `createServer({ name, version, tools: { greet } })`. The registration key becomes the name clients discover and call. Reuse the same tool definition across servers and transports. ## Build around your application * **Types follow your schemas.** Input and declared output schemas check handler types and parse runtime values, including defaults and transforms. * **Tools compose.** Keep definitions alongside the application services they expose, then choose which tools each server registers. * **Choose your transport.** Use stdio, start a Node HTTP listener, or mount a Web or Node handler in an existing application. * **Add dependencies and authorization.** Resolve services through typed, lazy context providers and protect HTTP endpoints with JWT or Clerk OAuth. Toolgrain implements MCP directly, independently of `@modelcontextprotocol/sdk`. ## Choose your packages Start with `@toolgrain/mcp` and a transport package. Install the same version across Toolgrain libraries. | Package | What it provides | | - | - | | [`@toolgrain/mcp`](/reference/mcp) | Tool definitions, servers, validation, rich results, and request context | | [`@toolgrain/node`](/reference/node) | Stdio, a managed HTTP listener, and Node HTTP handlers | | [`@toolgrain/http`](/reference/http) | Web `Request`/`Response` handlers for existing applications | | [`@toolgrain/jwt`](/reference/jwt) | JWT access-token verification for HTTP endpoints | | [`@toolgrain/clerk`](/reference/clerk) | Clerk OAuth access-token verification for HTTP endpoints | | [`@toolgrain/react`](/mcp-apps/reference) | Native MCP Apps browser lifecycle and typed React hooks | | [`@toolgrain/protocol`](/reference/protocol) | Pinned MCP wire types and protocol version constants | ## Compatibility and scope | Requirement | Supported | | - | - | | Module format | ESM | | Node.js | `^24.20.0` | | Bun applications | `>=1.4.4 <2` | | TypeScript | 5.5.4 or later, with strict mode | | Zod | `^4.6.6`, Classic or Mini | | MCP revisions | `2026-07-28` and `2025-06-18` | Both MCP revisions use the same tool API over stdio and HTTP. HTTP uses independent POST requests with JSON responses or request-scoped SSE progress. Fixed resources support [listing and reading text/binary content](/guides/resources). [Native React MCP Apps](/mcp-apps/overview) are available in Toolgrain 0.3.0 or later. Resource templates, sessions, resumability, prompts, elicitation, and subscriptions are outside the current implementation. See the [support policy](/project/support-policy) for runtime and dependency commitments, and [client compatibility](/compatibility/protocol) for verified client versions and flows. ## For AI agents Give your AI assistant [`llms.txt`](https://toolgrain.mintlify.site/llms.txt) for the documentation index or [`llms-full.txt`](https://toolgrain.mintlify.site/llms-full.txt) for the complete documentation. ## Go further > [card] [Tool authoring](/tools/overview) > > Define schemas, return rich content, and use request context and cancellation. > [card] [Context providers](/guides/context) > > Connect tools to databases and services with request-scoped caching. > [card] [HTTP and frameworks](/transports/overview) > > Pick a listener or handler that fits your application. > [card] [Authorization](/guides/authorization) > > Verify access tokens and read verified identities in your tools. # Add more widgets Source: https://toolgrain.mintlify.app/mcp-apps/build Build one self-contained HTML file per widget and register one resource for each. Continue from [Build your first widget](/mcp-apps/quickstart). Add a sales widget alongside weather, using the same Vite project and typed bindings. | Tool | Vite entry | Built file | Resource URI | | - | - | - | - | | `weather` | `weather.html` | `dist/widgets/weather.html` | `ui://weather/widget.html` | | `sales` | `sales.html` | `dist/widgets/sales.html` | `ui://sales/widget.html` | Each HTML file is an independent widget. A host creates an instance of the widget associated with the tool it calls. ## 1. Add the sales tool Replace `server/tools.ts` with the two-tool version: ```ts server/tools.ts theme={null} import { tool } from "@toolgrain/mcp"; import { z } from "zod"; export const weatherWidgetUri = "ui://weather/widget.html"; export const salesWidgetUri = "ui://sales/widget.html"; export const tools = { weather: tool({ description: "Show demo weather for a city.", input: z.object({ city: z.string().default("Dubai") }), output: z.object({ city: z.string(), temperature: z.number() }), _meta: { ui: { resourceUri: weatherWidgetUri } }, execute: ({ city }) => ({ city, temperature: city === "London" ? 14 : 29 }), }), sales: tool({ description: "Show demo sales for a region.", input: z.object({ region: z.string().default("West") }), output: z.object({ region: z.string(), total: z.number() }), _meta: { ui: { resourceUri: salesWidgetUri } }, execute: ({ region }) => ({ region, total: region === "West" ? 31000 : 42000 }), }), }; ``` The existing `createApp()` now knows both tool names. In the quickstart's `Weather` component, select its tool explicitly so TypeScript narrows the result: ```tsx theme={null} const { result, error, status } = useToolResult("weather"); ``` If you added the refresh example, it already selects `weather` by name. ## 2. Add the sales component and entry ```tsx src/Sales.tsx theme={null} import { AppProvider, useToolResult } from "./mcp.ts"; function SalesView() { const { result, error } = useToolResult("sales"); if (error) return

{error.message}

; if (result?.isError) return

Sales could not be loaded.

; const sales = result?.structuredContent; if (!sales) return

Waiting for sales…

; return (

{sales.region} sales

${sales.total.toLocaleString()}

); } export default function Sales() { return ( ); } ``` Create a React entry for that component: ```tsx src/sales-main.tsx theme={null} import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import "./index.css"; import Sales from "./Sales.tsx"; createRoot(document.getElementById("root")!).render( , ); ``` Add its HTML entry at the project root: ```html sales.html theme={null} Sales widget
``` ## 3. Build each entry separately The Vite configuration from the quickstart selects one HTML input from `--mode`: ```ts vite.config.ts theme={null} import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { viteSingleFile } from "vite-plugin-singlefile"; export default defineConfig(({ mode }) => ({ plugins: [react(), viteSingleFile()], publicDir: false, build: { outDir: "dist/widgets", emptyOutDir: mode === "weather", rolldownOptions: { input: `${mode}.html` }, }, })); ``` Update the `build` script in `package.json`: ```json theme={null} "build": "tsc -b && vite build --mode weather && vite build --mode sales" ``` Run it: ```sh theme={null} npm run build ``` The weather build clears `dist/widgets`; the sales build preserves it. The result contains **both** `weather.html` and `sales.html`, each with its own inlined JavaScript/CSS. Use one Vite build per HTML input with [vite-plugin-singlefile](https://github.com/richardtallent/vite-plugin-singlefile#readme). The plugin is designed for one HTML entry at a time; separate runs give each resource its own bundled dependencies. For a longer list of widgets, the repository's [build script](https://github.com/keshavkatwe/toolgrain/blob/main/apps/react-apps-example/scripts/build-widgets.mjs) runs the same sequence in a loop. ## 4. Register the second resource In `server/index.ts`, add `salesWidgetUri` to the import from `./tools.ts`. Before `createServer`, add the second resource: ```ts theme={null} const salesWidget = resource({ uri: salesWidgetUri, name: "sales-widget", mimeType: APPS_MIME_TYPE, read: async (uri) => ({ contents: [{ uri, mimeType: APPS_MIME_TYPE, text: await readFile(new URL("../dist/widgets/sales.html", import.meta.url), "utf8"), _meta: { ui: widgetUi }, }], }), }); ``` Register both definitions: ```ts theme={null} resources: [weatherWidget, salesWidget], ``` Both widgets reuse the same `widgetUi` settings here. Give a resource its own [metadata configuration](/mcp-apps/security) when it needs different permissions or network origins. Rebuild, reload the host's connector, and call `weather` and `sales`. Each tool points to its own resource URI and HTML entry. ## Assets and development Import local JavaScript, CSS, and assets from your widget's source so the bundler can include them. This recipe sets `publicDir: false`. If you enable Vite's `public` folder, its copied files are not automatically inlined by the single-file plugin. External scripts, fonts, images, and APIs need the appropriate [CSP origins](/mcp-apps/security#allow-network-requests-and-external-assets). `npm run dev` serves `/weather.html` and `/sales.html` during development. A normal browser tab has no MCP host connection. Rebuild the HTML and reload it in the host to test tool results and interactions. The repository example also has a `dev:ui` watch build for its shared entry. If several tools should intentionally render the same HTML application, use a [shared entry](/mcp-apps/shared-entries) with explicit routing instead. # Capabilities and fallbacks Source: https://toolgrain.mintlify.app/mcp-apps/capabilities Detect advertised Apps support without changing authorization or registration. `getAppSupport(ctx)` from `@toolgrain/mcp` returns: | Value | Meaning | | - | - | | `supported` | The current client advertises the Apps extension and required HTML MIME type | | `not-advertised` | Client capabilities are available but do not advertise that support | | `unknown` | This invocation has no client-capability context | The extension key is `io.modelcontextprotocol/ui`; its `mimeTypes` must include `text/html;profile=mcp-app`. Modern MCP requests carry their own capabilities. Legacy stdio retains claims from initialization. Independent legacy HTTP does not retain initialization state, so later calls return `unknown`. Toolgrain adds no session or transport-wide capability cache. Registration stays static. Every UI-enabled tool must provide meaningful text/JSON fallback content even when UI support is advertised. Capabilities can guide optional presentation work, but they must not decide whether an operation is authorized. The React iframe handshake negotiates host capabilities separately. `useToolCall` rejects when the host does not advertise server tool calls. Host themes and optional fields should have application fallbacks. ## React protocol support The Toolgrain 0.3.0 API exposes the provider and four hooks. Start with [`AppProvider` and `useToolResult()`](/mcp-apps/quickstart), then add optional hooks as needed. An upstream advertisement describes what a host can accept; only implemented APIs can send the corresponding requests. The provider advertises Apps `2026-01-26`. It also accepts an initialization reply selecting `2025-11-21`, used by older hosts such as the observed `grok-web` 1.0.0 build. The implemented message contracts are shared by these revisions; capability advertisements, message-source/origin checks, and payload validation still apply. Other Apps revisions are rejected. These UI revisions are independent of the outer MCP transport revision. | Wire feature | Toolgrain React behavior | | - | - | | `ui/initialize` and `ui/notifications/initialized` | Native provider handshake and revision check | | `tools/call` | `useToolCall`; requires advertised `serverTools` | | Tool input, result, and cancellation notifications | Retained initiating state through `useToolResult` | | `ui/notifications/tool-input-partial` | Ignored; the specification permits this. Only complete input is exposed | | Host context changes | `useHostContext`; optional theme/font application by the provider | | `ui/notifications/size-changed` | Automatic size reporting when enabled and ResizeObserver is available | | Host `ping` and `ui/resource-teardown` | Responded to natively; teardown closes the connection and cleans up | | `resources/read` from the widget | No public React resource-reading API | | `ui/open-link`, `ui/message`, `ui/update-model-context` | `useHostActions`; requires action and content-kind advertisements | | `ui/request-display-mode` | `useHostActions`; requires intersection of host/provider modes. Provider defaults to inline | | `ui/download-file` and `sampling/createMessage` | No public React API | | App-exposed tools and app-initiated teardown | Deferred; the provider does not advertise app tools | | Sandbox proxy setup | Host responsibility | `useHostContext()` reports the host's current display mode and available modes. The new action hook requests changes separately and returns the actual selected mode; live context still follows host notifications. A tool that refreshes data uses `useToolCall`, independently of the initiating result. The [dedicated protocol types](/mcp-apps/reference#server-and-wire-contracts) describe host capability advertisements, including optional actions outside this React API. They preserve extension fields. The reviewed upstream type file includes newer advertisements such as file downloads that are absent from the pinned stable prose specification; their presence is not a Toolgrain implementation or live-host compatibility claim. Host actions currently have automated fixture coverage, with live-host acceptance pending. Missing advertisements reject locally, even for older hosts that implement unadvertised actions. Use the [compatibility report](/mcp-apps/compatibility) for the exact tested host versions and transports. # Compatibility and acceptance Source: https://toolgrain.mintlify.app/mcp-apps/compatibility Verify hosts and diagnose widget connection problems. MCP Apps compatibility is host-version and transport specific. Protocol tests do not establish real host rendering compatibility. | Flow | Status | | - | - | | Native browser/React lifecycle | Covered by automated fixtures | | React host actions | Capability/modalities, requests/results, deadlines, cancellation, and cleanup covered by fixtures; no live-host acceptance yet | | Separate/shared HTML resources | Covered by the Bun/Elysia example checks | | Core revisions and fallback results | Covered by server/transport tests | | Claude Desktop 4.23118.0, macOS 26.5.2, local stdio | Separate/shared Weather and Sales rendering, metadata, refresh calls, and light/dark updates passed on 2026-11-06 | | Official Apps SDK 2.0.4 widget against Toolgrain | Passed with a self-authored DOM host fixture and direct MCP 2026-07-28 dispatch; not a live-host rendering claim | ## Stable publication verification On November 8, 2026, [Release PR #63](https://github.com/keshavkatwe/toolgrain/pull/63) merged as [`d067bbb`](https://github.com/keshavkatwe/toolgrain/commit/d067bbb8d1710b232d026d1f3754c9b0fd112d4f). The [release run](https://github.com/keshavkatwe/toolgrain/actions/runs/42451243089) published 0.3.0 for all seven libraries under npm's `latest` tag after the full release matrix passed. Downloaded archives matched the verified build artifacts; both npm metadata formats, registry integrity, and fresh npm/Node 24.20.0 and Bun 1.4.4 consumers passed. All seven versions include npm provenance. These checks verify published packages, declarations, and protocol flows. The live Claude Desktop record below retains its original version, date, and local stdio scope. Host actions and live HTTP widgets have no additional live-host acceptance from this publication run. ## Published alpha verification The [November 6, 2026 publication run](https://github.com/keshavkatwe/toolgrain/actions/runs/42244638853) completed `0.3.0-alpha.2` for all seven Toolgrain libraries. Registry checks matched the actual downloaded archives to the verified artifacts in both npm metadata formats. Fresh npm/Node 24.20.0 and Bun 1.4.4 consumers passed imports, minimum/current declarations, and stdio/HTTP flows. These publication checks are separate from the live Claude Desktop test below, which exercised the Apps implementation before the combined alpha publication. Published `0.3.0-alpha.3` adds named wire types and host actions; live-host acceptance for the new actions remains pending. Neither result establishes untested host versions or transports. ## Alpha.3 publication verification The [November 7, 2026 publication run](https://github.com/keshavkatwe/toolgrain/actions/runs/42393275595) completed `0.3.0-alpha.3` for all seven libraries from commit `9d9c3a2fef842d60beb229943c0bf0b6704cf835`. All seven downloaded npm archives matched the approved build; both npm metadata formats, existing `latest` tags, and fresh Node/Bun consumers passed verification. React's first CI/OIDC publication includes provenance identifying that source commit. This verifies package publication and automated consumers. The new host actions still have fixture coverage rather than live Claude Desktop acceptance. ## Vite walkthrough verification On November 7, 2026, the [Vite walkthrough](/mcp-apps/quickstart) was checked from a fresh `create-vite@9.3.4` React/TypeScript scaffold using published `0.3.0-alpha.3`, Node 24.22.2, Vite 8.3.4, and `vite-plugin-singlefile` 2.3.4. The initial widget, refresh component, typed resource/result metadata, and separate weather/sales builds compiled. Each output HTML contained its own JavaScript/CSS; real stdio tool calls and resource reads passed under both supported outer MCP revisions, including assistant fallback content. These are local build/compiler and protocol checks. The exact scaffold was not tested in a live Claude Desktop session; the separately recorded host test below retains its original scope. On November 8, 2026, the weather quickstart was rechecked from a fresh scaffold with published Toolgrain 0.3.0, Node 24.22.2, React 19.3.1, Vite 8.3.4, and `vite-plugin-singlefile` 2.3.4. The documented files compiled into a single HTML widget. Tool calls, assistant fallback text, resource listing/reading, the Apps MIME type, and resource metadata passed over real stdio in both supported MCP revisions. This check did not add live-host rendering coverage. ## Claude Desktop acceptance The recorded local test used Bun 1.4.4 to launch the built example's stdio entry. Claude advertised `io.modelcontextprotocol/ui` with the Apps HTML MIME type and negotiated outer MCP `2025-06-18`; the iframe negotiated Apps `2026-01-26`. Both separate entries and both metadata-routed shared entries displayed their expected data. City and region buttons updated each widget through host-mediated tool calls, and existing widgets followed light/dark host theme changes. The temporary connector and appearance changes were removed after testing. This verifies only that host version and local stdio configuration. Claude HTTP connections, host-driven cancellation, and host permission/CSP enforcement were not exercised live. Cancellation, errors, malformed traffic, lifecycle cleanup, and fallback envelopes are covered by automated fixtures; these checks do not establish host policy behavior. Build the example, then configure a local stdio connection launching its `start:stdio` command with a supported Bun runtime. Record the exact Claude Desktop version, OS, negotiated outer revision, Apps capabilities, and connection configuration without credentials or local machine paths. Call each separate tool and both shared tools. Confirm the expected widget, initial structured and metadata data, city/region buttons, host theme changes, expected errors, cancellation, and normal text fallback. Disconnect and confirm cleanup. For the new host actions, additionally record the host's action/content-kind advertisements and display modes. Test link opening, an explicit user message, replacement context on a later turn, and both requested/actual modes. Confirm unsupported controls and declined actions behave usefully. The recorded test above did not exercise these additions. For HTTP testing, configure the application's allowed hosts explicitly. Using a public connector or tunnel is a separate exposure/deployment decision; the example does not open one automatically. ## Interoperability acceptance Run `bun run test:interop` from the repository root. It builds an independently authored widget with pinned official SDK dependencies in a disposable installation outside the workspace. The fixture checks resource/security metadata, initialization, structured content/result metadata, a host-mediated call, and a theme update. Its report stays ignored under `reports/`. Use an independently built widget using the official Apps SDK, served by a Toolgrain resource and tool. Verify initial results, host-mediated tool calls, and security metadata. Keep SDK dependencies confined to that external acceptance fixture, outside Toolgrain's runtime packages. ## Grok compatibility candidate — November 9, 2026 The unreleased compatibility fix accepts the `2025-11-21` Apps initialization reply observed from `grok-web` 1.0.0 while continuing to request `2026-01-26`. Published React 0.3.0 rejects that reply with `Unsupported MCP Apps revision`. The host build inspected was [`3oyj98v985_o5.js`](https://cdn.grok.com/_next/static/chunks/3oyj98v985_o5.js); its identity and behavior may change independently of its reported version. A consumer widget rebuilt with the candidate was loaded in an existing Grok conversation through a temporary local sandbox-response override. Grok's host code and initialization reply were unchanged. The widget completed initialization, rendered its real initiating account result, and completed a manual refresh through the host's tool proxy. The override configuration was removed afterward. This is candidate acceptance, not verification of a published Toolgrain fix or a deployed consumer release. Other host actions, permission policies and quota widgets were not verified live in this test. The captured handshake has regression coverage for both accepted revisions, initiating results, host context, sizing, open links, refresh calls, cancellation, teardown, source/origin checks, invalid payloads and unreviewed revisions. These fixtures do not establish every older host's behavior or widen the supported outer MCP revisions. ## Troubleshooting A connection timeout usually means the page was opened without an Apps host, the host does not support Apps, or its iframe handshake did not complete. Verify the resource MIME type and tool URI. A routing error means a shared entry could not select a tool; inspect its application-owned marker. An unsupported tool-call error means the host did not advertise serverTools. Inspect errors and preserve useful assistant content for all cases. Claude Desktop cached resource HTML for a connector instance during the recorded test. Restarting the temporary connector was needed to test changed HTML; starting a new chat alone did not reload it. Recheck this behavior when testing another host version. # React host actions Source: https://toolgrain.mintlify.app/mcp-apps/host-actions Open links, send messages, share context, and request display modes through the host. > [!NOTE] > > These actions are available in Toolgrain 0.3.0 or later. They have automated fixture coverage; live-host acceptance remains pending. Add `useHostActions` to the exports from your existing `src/mcp.ts` factory. The hook shares that provider's connection and sends no requests until you call an action. ```tsx theme={null} import { useState } from "react"; import { useHostActions } from "./mcp.ts"; function SourceLink() { const { available, openLink } = useHostActions(); const [error, setError] = useState(); async function openSource() { setError(undefined); try { const result = await openLink("https://github.com/keshavkatwe/toolgrain"); if (result.isError) setError("The host declined the link."); } catch { setError("The link could not be opened."); } } return ( <> {error ?

{error}

: null} ); } ``` Keep requests in explicit interaction handlers when they affect the conversation or open another application. Your component owns pending, success, and error state; the hook supplies stable action functions without a request cache. ## Check availability `available` contains `openLink`, `sendMessage`, `updateModelContext`, and `displayModes`. Before initialization and after closure, booleans are false and modes are empty. Availability follows host-context changes. The first three actions require explicit `openLinks`, `message`, and `updateModelContext` host capability advertisements respectively. Message and context requests also require every supplied content kind to be advertised, such as `text: {}` or `structuredContent: {}`. An availability boolean reports the action's advertisement; a particular payload can still be unsupported. Missing advertisements reject locally without posting a request, including with older hosts that implement an action without advertising it. ## Open a link `openLink(url, options?)` sends `ui/open-link` with an absolute URL. The host chooses whether and how to open it, applying its own URL and permission policy. Toolgrain does not open a browser window itself. ## Send a user message `sendMessage(params, options?)` sends `ui/message`. The role must be `user` and `content` is an array of MCP content blocks. Sending can add a message to the conversation and trigger a model follow-up; the host may request consent. ```ts theme={null} const result = await actions.sendMessage({ role: "user", content: [{ type: "text", text: "Explain the selected sales region." }], }); if (result.isError) showError("The host declined the message."); ``` ## Update future model context `updateModelContext(params, options?)` sends `ui/update-model-context`. Pass optional `content` blocks, object-root `structuredContent`, or both. Each update replaces the app's previously submitted context. An empty object submits an empty replacement. ```ts theme={null} const result = await actions.updateModelContext({ structuredContent: { region: "West", total: 31000 }, }); if (result.isError) showError("The host declined the context update."); ``` This does not itself request a model follow-up. The host may defer the context until a future user message and may deduplicate updates. It remains separate from your initiating tool result and `useToolCall` state. ## Request a display mode Declare every mode the widget can render on the provider. The default is `["inline"]`; this declaration stays fixed until remount. ```tsx theme={null} ``` `available.displayModes` is the intersection of this declaration and the host's `availableDisplayModes`. If the host omits its modes, the intersection is empty. Only request a mode in that list: ```ts theme={null} if (actions.available.displayModes.includes("fullscreen")) { const result = await actions.requestDisplayMode("fullscreen"); showStatus(`Host selected ${result.mode}`); } ``` The host may return a different mode, such as `inline`. A response selecting a mode the app never declared rejects. The returned result describes this request's outcome; `useHostContext().displayMode` continues to follow host notifications. The hook does not synthesize context changes from responses. The `pip` mode is also available when both app and host advertise it. ## Results, deadlines, and cancellation All four actions return the complete validated host response, including extension fields. Link, message, and context acknowledgements may contain `isError: true`; these resolve so callers can inspect the denial. Display requests return `{ mode, ...extensions }`. JSON-RPC errors, invalid replies, unsupported requests, and transport failures reject. Each function accepts an optional `HostActionOptions` with `signal` and `timeoutMs`. The provider's deadline defaults to 30 seconds; an action can override it. Local abort or timeout rejects the promise, sends a cancellation notification, and suppresses late replies. Cancellation is cooperative and cannot undo an action the host already performed. Teardown rejects pending actions and removes owned timers/listeners. See the [API reference](/mcp-apps/reference), [support table](/mcp-apps/capabilities#react-protocol-support), and [acceptance scope](/mcp-apps/compatibility). The repository's React example includes all four controls with caller-owned pending/error state. # MCP Apps Source: https://toolgrain.mintlify.app/mcp-apps/overview Build a React widget, bundle it as HTML, and return it with a Toolgrain tool. An MCP App is an HTML widget that a compatible MCP host displays when it calls your tool. Your server still returns useful data for the assistant; the widget adds a React interface beside it. Start with [Build your first widget](/mcp-apps/quickstart). It begins with the Vite CLI and shows every file you need to edit. ## The three pieces | Piece | What you write | | - | - | | Tool | A normal Toolgrain `tool()` that returns data and points to a widget URI | | Widget | React components using `AppProvider` and `useToolResult()` | | Resource | A `resource()` that returns the widget's built HTML | Vite turns `weather.html` into `dist/widgets/weather.html`. The resource serves that file under a URI such as `ui://weather/widget.html`. The host loads the HTML and delivers the tool result to React. Toolgrain handles the native Apps connection, result delivery, host styling, and widget sizing. Your application owns its UI and build. The host owns iframe creation, sandboxing, CSP enforcement, and permission grants. ## Follow the guides in order 1. [Build your first widget](/mcp-apps/quickstart): scaffold a React app, add the tool and resource, and connect a host. 2. [Use React hooks](/mcp-apps/react): add refresh calls, loading/error states, and optional host context. 3. [Add more widgets](/mcp-apps/build): build a separate HTML file for each resource. 4. [Permissions and metadata](/mcp-apps/security): edit one configuration object for the widget's needs. For existing servers, use [Link tools and widgets](/mcp-apps/server). [Shared entries](/mcp-apps/shared-entries) and [host actions](/mcp-apps/host-actions) are optional follow-ups. > [!NOTE] > > Apps and React are available in Toolgrain 0.3.0 or later. Install matching versions across Toolgrain packages. [Compatibility and acceptance](/mcp-apps/compatibility) records exact tested builds and live-host coverage. Toolgrain implements the Apps protocol natively, without the official MCP or Apps SDKs. The iframe uses Apps revision `2026-01-26`, independently of the outer MCP connection. See the [protocol support table](/mcp-apps/capabilities#react-protocol-support) for the implemented messages. # Build your first widget Source: https://toolgrain.mintlify.app/mcp-apps/quickstart Start with the Vite CLI and connect a React widget to a Toolgrain tool. Build a small weather widget from a new React project. A tool returns the weather, Vite builds the widget into one HTML file, and your MCP host displays it. Use **Node 24.20.0 or later in Node 24**, npm, and matching **Toolgrain 0.3.0 or later** packages. The Vite build recipe is pinned so you can reproduce it. ## 1. Create a Vite project Run the [Vite CLI](https://vite.dev/guide/#scaffolding-your-first-vite-project) with its React and TypeScript template: ```sh theme={null} npm create vite@9.3.4 weather-app -- --template react-ts --no-interactive --no-immediate cd weather-app npm install ``` Add Toolgrain and the single-file build plugin: ```sh theme={null} npm install --save-exact @toolgrain/react @toolgrain/mcp @toolgrain/node @toolgrain/protocol zod@^4.6.6 npm install --save-dev --save-exact vite@8.3.4 vite-plugin-singlefile@2.3.4 ``` Use matching Toolgrain 0.3.0 or later versions. The commands resolve npm's `latest` tag and save exact versions in your application. ## 2. Define the tool Create a `server` folder and add this file. The tool's registration key, `weather`, is also the name React will use. ```ts server/tools.ts theme={null} import { tool } from "@toolgrain/mcp"; import { z } from "zod"; export const weatherWidgetUri = "ui://weather/widget.html"; export const tools = { weather: tool({ description: "Show demo weather for a city.", input: z.object({ city: z.string().default("Dubai") }), output: z.object({ city: z.string(), temperature: z.number() }), _meta: { ui: { resourceUri: weatherWidgetUri } }, execute: ({ city }) => ({ city, temperature: city === "London" ? 14 : 29, }), }), }; ``` This is deterministic demo data. Toolgrain converts the returned object into structured content and assistant-facing text, so the tool also works in clients that do not display widgets. ## 3. Create the React bindings Add one small module that connects your components to the tool types: ```ts src/mcp.ts theme={null} import { createApp } from "@toolgrain/react"; import type { tools } from "../server/tools.ts"; export const { AppProvider, useToolResult } = createApp(); ``` The `import type` is important: it gives React the tool's input/output types without bundling the server code. Create these bindings once, outside your components. ## 4. Replace the starter component Replace `src/App.tsx`: ```tsx src/App.tsx theme={null} import { AppProvider, useToolResult } from "./mcp.ts"; function Weather() { const { result, error, status } = useToolResult(); if (error) return

{error.message}

; if (result?.isError) return

Weather could not be loaded.

; const weather = result?.structuredContent; if (!weather) { return

{status === "cancelled" ? "Request cancelled." : "Waiting for weather…"}

; } return (

{weather.city}

{weather.temperature}°C

); } export default function App() { return ( ); } ``` **One provider and one hook are enough to display a result.** The provider connects to the host, applies its theme, and reports widget size. `useToolResult()` receives the initiating tool result. The host creates the widget when the tool is called. Replace the starter's full-page styles with a widget layout: ```css src/index.css theme={null} :root { font-family: var(--font-sans, system-ui, sans-serif); color: var(--color-text-primary, #1f2937); background: var(--color-background-primary, #fff); } body { margin: 0; padding: 16px; } h1 { margin: 0 0 8px; font-size: 22px; } p { margin: 8px 0; } ``` ## 5. Configure one HTML build Rename the generated `index.html` to `weather.html` and replace its contents: ```html weather.html theme={null} Weather widget
``` The generated `src/main.tsx` renders the `App` you replaced. Now replace `vite.config.ts`: ```ts vite.config.ts theme={null} import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { viteSingleFile } from "vite-plugin-singlefile"; export default defineConfig(({ mode }) => ({ plugins: [react(), viteSingleFile()], publicDir: false, build: { outDir: "dist/widgets", emptyOutDir: mode === "weather", rolldownOptions: { input: `${mode}.html` }, }, })); ``` In `package.json`, set the `build` script and add `start:mcp`: ```json theme={null} { "scripts": { "build": "tsc -b && vite build --mode weather", "start:mcp": "node server/index.ts" } } ``` Merge those entries into the existing `scripts` object. In `tsconfig.node.json`, add `server` to `include` so the build also checks your server files: ```json theme={null} "include": ["vite.config.ts", "server"] ``` `--mode weather` selects `weather.html`. The plugin inlines its JavaScript and CSS into **`dist/widgets/weather.html`**. `publicDir: false` skips the starter's public assets; the HTML above also removes its favicon/logo references. ## 6. Serve the HTML as a resource Create the MCP server. Keep the widget's presentation and permission settings in the named `widgetUi` object: ```ts server/index.ts theme={null} import { readFile } from "node:fs/promises"; import { createServer, resource } from "@toolgrain/mcp"; import { stdio } from "@toolgrain/node"; import { APPS_MIME_TYPE, type AppResourceMeta } from "@toolgrain/protocol/apps"; import { tools, weatherWidgetUri } from "./tools.ts"; const widgetUi = { prefersBorder: true, } satisfies AppResourceMeta; const weatherWidget = resource({ uri: weatherWidgetUri, name: "weather-widget", mimeType: APPS_MIME_TYPE, read: async (uri) => ({ contents: [{ uri, mimeType: APPS_MIME_TYPE, text: await readFile(new URL("../dist/widgets/weather.html", import.meta.url), "utf8"), _meta: { ui: widgetUi }, }], }), }); const server = createServer({ name: "weather-app", version: "1.0.0", tools, resources: [weatherWidget], }); await server.listen(stdio()); ``` The tool's `resourceUri` and the resource's `uri` must match exactly. The resource reads your built file; a `ui://` URI is an identifier, not a filesystem location. The HTML MIME type appears on both the resource definition and the returned content. To request permissions or allow network origins later, edit `widgetUi` using the [permissions and metadata guide](/mcp-apps/security). ## 7. Build and connect a host ```sh theme={null} npm run build ``` You should have `dist/widgets/weather.html`, with its script and styles inside it. The server runs with `npm run start:mcp`. It waits for MCP messages over stdio; it does not open a browser or print a startup message to stdout. [Node 24 runs these TypeScript server files directly](https://nodejs.org/docs/latest-v24.x/api/typescript.html#type-stripping). In Claude Desktop, open **Settings → Developer → Edit Config** ([host setup guide](https://modelcontextprotocol.io/docs/develop/connect-local-servers)). Add the following entry to its `mcpServers` object, using your Node executable and the absolute server entry path: ```json theme={null} { "mcpServers": { "toolgrain-weather": { "command": "/absolute/path/to/node", "args": ["/absolute/path/to/weather-app/server/index.ts"] } } } ``` Find your Node executable with `node -p "process.execPath"`. Replace both paths, save the configuration, and restart Claude Desktop to load it. Ask Claude to call `weather` with `{ "city": "Dubai" }`. An Apps-capable host should load the widget and supply that tool's result. Opening `weather.html` directly, or visiting Vite's dev server, does not create an MCP host connection. Test the connected widget inside a compatible host. See [host testing and troubleshooting](/mcp-apps/compatibility) for the recorded environments, setup details, and resource-cache behavior. ## Next steps * [Add a refresh button](/mcp-apps/react#add-a-refresh-button) with `useToolCall`. * [Add a second widget](/mcp-apps/build) with one HTML file and resource per widget. * [Request permissions or network access](/mcp-apps/security) in `widgetUi`. * [Use host actions](/mcp-apps/host-actions) when you need links, messages, or display-mode requests. # Use React hooks Source: https://toolgrain.mintlify.app/mcp-apps/react Start with one result hook and add interactive calls only when you need them. The [first widget](/mcp-apps/quickstart) uses one provider and one hook. Add the other hooks as the widget gains features. | You want to… | Use | | - | - | | Connect the widget to its host | `AppProvider` around the component tree | | Display the tool's initial result | `useToolResult()` | | Refresh or filter by calling a tool | `useToolCall("tool_name")` | | Read locale, current display mode, or other host hints | `useHostContext()` | | Open a link, send a message, share context, or change display mode | [`useHostActions()`](/mcp-apps/host-actions) | Create the bindings once in `src/mcp.ts`. Components import the hooks from that file. Every hook runs inside that factory's `AppProvider`. ## Display the first result ```tsx theme={null} const { result, error, status } = useToolResult(); ``` `result` is the complete initiating tool result. Its `structuredContent` contains the typed data you returned on the server. It can be absent while waiting, after cancellation, or when a tool fails. Handle `error`, `result?.isError`, and missing data before rendering the result, as shown in the quickstart. With several tools in the map, use `useToolResult("weather")` to select the expected tool's type. An unnamed result is a union you can narrow by `state.toolName`. ## Add a refresh button First, export `useToolCall` alongside your existing bindings: ```ts src/mcp.ts theme={null} import { createApp } from "@toolgrain/react"; import type { tools } from "../server/tools.ts"; export const { AppProvider, useToolResult, useToolCall } = createApp(); ``` In `src/App.tsx`, import `useToolCall` from `./mcp.ts`. Replace the `Weather` component with this version; keep it inside the provider: ```tsx theme={null} function Weather() { const initial = useToolResult("weather"); const refresh = useToolCall("weather"); const result = refresh.result ?? initial.result; if (initial.error) return

{initial.error.message}

; if (result?.isError) return

The tool reported a weather error.

; const weather = result?.structuredContent; if (!weather) return

Waiting for weather…

; return (

{weather.city}

{weather.temperature}°C

{refresh.error ?

Refresh failed. Try again.

: null}
); } ``` `useToolCall` returns `call`, `pending`, `result`, and `error`. The catch prevents an unhandled rejection; the hook stores the failure in `refresh.error`, which the component displays. The host must advertise server tool-call support. The initial result and refresh result are separate. `refresh.result ?? initial.result` displays the latest successful call or the original data. The hook does not overwrite `useToolResult()` or start calls automatically. ## Interactive calls `call(input, options?)` returns the full result. Explicit `isError: true` tool results resolve normally; transport and JSON-RPC failures reject. Concurrent calls each settle their promises, while the latest invocation owns the hook's displayed state. Options are optional: ```ts theme={null} const controller = new AbortController(); await refresh.call({ city: "London" }, { timeoutMs: 10_000, signal: controller.signal, }); ``` The default deadline is 30 seconds. An abort or timeout rejects locally and suppresses late replies. Host cancellation remains cooperative. ## Read host context when needed The provider already applies host fonts and theme variables. CSS such as `var(--color-text-primary, #1f2937)` is enough for the basic widget. Export `useHostContext` from `src/mcp.ts` when you need host information in React logic: ```tsx theme={null} const { locale, timeZone, displayMode } = useHostContext(); ``` These hints are optional. Supply application defaults, such as `locale ?? "en"`. Use [host actions](/mcp-apps/host-actions) to request a display-mode change or another explicit host operation. ## Inferred types Tool names come from registration keys. Arguments use the input schema's input type, before defaults/transforms. Structured results use the parsed output schema type. Result `_meta` retains the type inferred from `mcpResult()`. `structuredContent` and `_meta` remain optional. Toolgrain validates the wire envelopes; application payload types are inferred rather than schema-validated in the browser. See [metadata](/mcp-apps/security#extra-widget-data) for an example. ## Provider lifecycle Use one provider per widget window. Pass `appInfo` and either `tool` for a separate entry or `resolveTool` for a [shared entry](/mcp-apps/shared-entries). Identity, routing, and declared display modes are fixed for that mount. The factory is safe to import during server rendering. Mounting connects to the host; React Strict Mode reuses the connection during effect replay. Unmount/host teardown removes owned listeners, observers, and timers and rejects pending requests. Remount to reconnect. Host styling and automatic size reporting default to on. Disable them with `applyHostStyles={false}` or `autoResize={false}` when your application needs to manage them. See the [API reference](/mcp-apps/reference) for the complete provider options and state contracts. # React and Apps API reference Source: https://toolgrain.mintlify.app/mcp-apps/reference Public bindings, provider options, and protocol exports. ## createApp `createApp()` from `@toolgrain/react` returns `AppProvider`, `useToolResult`, `useToolCall`, `useHostContext`, and `useHostActions`. It does not read browser globals or connect until mounting. > [!NOTE] > > This reference describes the stable Toolgrain 0.3.0 API. Start with the [Vite walkthrough](/mcp-apps/quickstart) for a runnable project, then add only the hooks your widget uses. ## AppProvider | Prop | Contract | | - | - | | `appInfo` | Required nonempty name/version; fixed for the mount | | `tool` | A registered tool name for a separate entry; exclusive with `resolveTool` | | `resolveTool` | Shared-entry selector receiving result and host context; returns a registered name or undefined | | `timeoutMs` | Positive integer deadline, default 30000 milliseconds | | `hostOrigin` | Optional exact parent origin; default allows opaque sandbox origins | | `applyHostStyles` | Apply/restore host fonts and CSS variables, default true | | `autoResize` | Report size through ResizeObserver when available, default true | | `availableDisplayModes` | Nonempty readonly list of modes this widget supports; default `["inline"]`, fixed for the mount | | `children` | React component tree sharing this connection | A connection is terminal after closure. Remount to reconnect or change identity/routing. Unmount and teardown remove owned resources. Server rendering does not connect. ## Hooks `useToolResult(name?)` returns status, selected tool name, optional original wire input, full result, and lifecycle/routing error. Without a name, the selected name discriminates the registered tool union. With a name, other active tools appear as waiting. `useToolCall(name)` returns `call(input, options?)`, pending, optional full result, and optional error. Options accept AbortSignal and timeoutMs. Explicit tool errors resolve; RPC/transport failures reject. Each hook tracks its latest invocation independently of the initiating result. `useHostContext()` returns live `AppHostContext`. Fields are optional and self-reported by the host. `useHostActions()` returns `available` and stable request functions: | Function | Parameters | Resolved result | | - | - | - | | `openLink` | Absolute URL string, optional request options | `AppActionResult` | | `sendMessage` | `AppMessageParams`, optional request options | `AppActionResult` | | `updateModelContext` | `AppModelContextParams`, optional request options | `AppActionResult` | | `requestDisplayMode` | `AppDisplayMode`, optional request options | `AppDisplayModeResult` | Request options accept `signal` and `timeoutMs`; the provider default is 30000 milliseconds. Capability/content checks happen before sending. Explicit `isError` acknowledgements resolve; RPC/transport/validation failures reject. The hook owns no pending/error state. See [host actions](/mcp-apps/host-actions) for availability, replacement context, and actual display-mode behavior. Exported authoring types: `AppProviderProps`, `AppState`, `ToolState`, `ToolName`, `ToolInput`, `ToolResult`, `ToolCall`, and `ToolCallOptions`. Host-action types are `HostActions`, `HostActionAvailability`, and `HostActionOptions`. ## Server and wire contracts `getAppSupport(ctx)` and `AppSupport` are exported by `@toolgrain/mcp`. Existing `mcpResult()` types preserve inferred metadata through an optional second generic parameter; existing single-generic usage remains valid. `@toolgrain/protocol/apps` exports `APPS_PROTOCOL_VERSION`, `APPS_EXTENSION_ID`, `APPS_MIME_TYPE`, `AppToolMeta`, `AppResourceMeta`, `AppHostContext`, `AppHostCapabilities`, `AppDisplayMode`, `AppToolResult`, `AppInitializeParams`, and `AppInitializeResult`. This export has no runtime dependencies and does not replace either supported outer MCP revision. Additional named exports describe resource settings, host presentation, and host-action envelopes: | Type | Contract | | - | - | | `AppResourceCsp` | Readonly domain lists for network, resource, nested-frame, and base-URI CSP directives | | `AppResourcePermissions` | Camera, microphone, geolocation, and clipboard-write requests expressed as empty objects | | `AppTheme` | `light` or `dark` | | `AppStyleVariableKey` | Standardized color, typography, radius, border-width, and shadow token names | | `AppStyleVariables` | Optional standard variables plus string-valued host/application extensions | | `AppHostCss` | Host font-loading CSS and extension fields | | `AppHostStyles` | Variables and CSS supplied in host context | | `AppContentModalities` | Content kinds advertised for optional host actions | | `AppMessageParams` | User role and readonly MCP content-block array | | `AppModelContextParams` | Optional content blocks and object-root structured replacement context | | `AppActionResult` | Host acknowledgement with optional `isError` and preserved extensions | | `AppDisplayModeResult` | Actual selected display mode and preserved extensions | `AppHostCapabilities` now names sandbox grants/CSP, experimental extensions, content-message/context modalities, download support, and sampling tools, alongside existing server tool/resource, link, and logging advertisements. Unknown capability fields are preserved. The [support table](/mcp-apps/capabilities#react-protocol-support) distinguishes implemented requests from other advertisements. Styling variables are optional. Use CSS fallbacks such as `var(--color-text-primary, #111)` and `var(--font-sans, sans-serif)`. The provider applies supplied variables and font CSS by default; `applyHostStyles={false}` disables that behavior. The metadata guide includes [resource fields and border examples](/mcp-apps/security#resource-metadata). `AppToolMeta` rejects resource-only CSP/permissions, including when metadata is assigned through another variable. The runtime still preserves supplied metadata; the host owns enforcement. `apps-provenance.json` pins the reviewed [stable specification](https://github.com/modelcontextprotocol/ext-apps/blob/298e884ec3f02daba085acdb02042d73bd00b355/specification/2026-01-26/apps.mdx) and [upstream type reference](https://github.com/modelcontextprotocol/ext-apps/blob/040942b3af064bf76b705021e3472b6593ae839e/src/spec.types.ts), including their SHA-256 hashes. Some type-reference advertisements go beyond the stable prose; their presence alone does not implement a React action. # Permissions and metadata Source: https://toolgrain.mintlify.app/mcp-apps/security Keep widget settings in one object and put each kind of metadata in the right place. The quickstart's `server/index.ts` has one place to configure the widget: ```ts theme={null} const widgetUi = { prefersBorder: true, } satisfies AppResourceMeta; ``` Edit that object as the widget needs more capabilities. Import `AppResourceMeta` as a type from `@toolgrain/protocol/apps` for autocomplete and field checking. ## Request a permission For example, a widget that copies a value to the clipboard can request: ```ts theme={null} const widgetUi = { prefersBorder: true, permissions: { clipboardWrite: {} }, } satisfies AppResourceMeta; ``` Use empty objects, such as `{ clipboardWrite: {} }`, rather than booleans. Other permission names are `camera`, `microphone`, and `geolocation`. Request only the permissions your widget uses. A declaration asks the host for access; the host can deny it. Check the browser API is available and handle permission denial in the widget's interaction handler. ## Allow network requests and external assets If the React code itself fetches a remote API, add its origin: ```ts theme={null} const widgetUi = { prefersBorder: true, permissions: { clipboardWrite: {} }, csp: { connectDomains: ["https://api.example.com"], resourceDomains: ["https://images.example.com"], }, } satisfies AppResourceMeta; ``` `connectDomains` covers fetch, XHR, and WebSocket connections. `resourceDomains` covers external scripts, styles, fonts, images, and media. Use explicit origins, not paths to individual API methods or images. The host may restrict them further. The quickstart bundles its JavaScript/CSS into HTML and needs no external origins. Calls made with `useToolCall` travel through the host; add a network origin when your widget makes the network request itself. ## Put settings on the returned HTML The `widgetUi` object belongs on each resource content item's `_meta.ui`. The quickstart already places it here: ```ts theme={null} contents: [{ uri, mimeType: APPS_MIME_TYPE, text: builtHtml, _meta: { ui: widgetUi }, }], ``` Here, `builtHtml` is the string read from your built widget file. Putting permissions/CSP on the tool, or only on the outer resource-read result, does not configure the widget sandbox. ## Resource metadata | Setting inside `widgetUi` | Use it for | | - | - | | `prefersBorder: true` | Request a host-provided border and background | | `prefersBorder: false` | Request neither; omit the field to let the host choose | | `permissions` | Request camera, microphone, geolocation, or clipboard-write access | | `csp.connectDomains` | Origins your widget contacts with fetch/XHR/WebSocket | | `csp.resourceDomains` | Origins serving external scripts, styles, fonts, images, or media | | `csp.frameDomains` | Origins for nested iframes | | `csp.baseUriDomains` | Allowed document base URIs | | `domain` | A dedicated sandbox origin in the host's required format | Omitted network/frame origins do not allow arbitrary connections or nested frames. The default base URI is restricted to the sandbox's own origin. A `domain` request does not configure DNS, host allowlists, or OAuth callbacks. Recheck domain/permission behavior for the host you target; the [acceptance record](/mcp-apps/compatibility) lists what was actually exercised. ## Three kinds of metadata | Where it goes | What belongs there | | - | - | | Tool definition: `_meta.ui` | `resourceUri` and optional `visibility` | | Returned HTML content: `_meta.ui` | The `widgetUi` permissions, CSP, border, and domain settings above | | Tool result: `_meta` | Extra application data for the widget, such as chart points or a routing marker | See [tool linking and visibility](/mcp-apps/server#tool-linking-and-visibility) for app-only refresh/filter tools. ## Extra widget data Use `mcpResult()` when the tool also needs result metadata. For example, replace the weather tool's `execute` function and import `mcpResult` from `@toolgrain/mcp`: ```ts theme={null} execute: ({ city }) => mcpResult({ content: [{ type: "text", text: `Demo weather for ${city}.` }], structuredContent: { city, temperature: city === "London" ? 14 : 29 }, _meta: { forecast: [24, 26, 29, 27] }, }), ``` React receives the full envelope, including the inferred metadata type: ```tsx theme={null} const { result } = useToolResult("weather"); const forecast = result?._meta?.forecast; ``` Keep result `_meta` optional in your component: errors or protocol conversion can omit it. Continue returning meaningful content for the assistant. Shared entries can use an application-owned marker such as `_meta.view` for [routing](/mcp-apps/shared-entries). ## Connection and authorization The host owns iframe creation, sandboxing, CSP enforcement, and permission grants. Toolgrain's browser connection accepts messages from the embedding parent and validates known wire envelopes. `hostOrigin` can restrict that parent to an exact origin; hosts using opaque sandbox origins may need the default setting. Permissions, capability claims, and routing metadata do not establish identity or authorize server work. Preserve [endpoint authentication and application authorization](/authentication/overview) for tool calls and resource reads. Never put bearer credentials or server services in widget HTML. Use `import type` for the tool map and validate application data when your UI requires it. The [reviewed Apps resource contract](https://github.com/modelcontextprotocol/ext-apps/blob/298e884ec3f02daba085acdb02042d73bd00b355/specification/2026-01-26/apps.mdx#ui-resource-format) defines the wire fields. # Link tools and widgets Source: https://toolgrain.mintlify.app/mcp-apps/server Attach built HTML widgets to tools in an existing Toolgrain server. Start with [Build your first widget](/mcp-apps/quickstart) for a complete new project. In an existing Toolgrain server, the integration has three parts. ## 1. Define the HTML resource Use `resource()` to return the HTML produced by your Vite build: ```ts theme={null} import { readFile } from "node:fs/promises"; import { resource } from "@toolgrain/mcp"; import { APPS_MIME_TYPE, type AppResourceMeta } from "@toolgrain/protocol/apps"; const widgetUi = { prefersBorder: true } satisfies AppResourceMeta; const weatherWidget = resource({ uri: "ui://weather/widget.html", name: "weather-widget", mimeType: APPS_MIME_TYPE, read: async (uri) => ({ contents: [{ uri, mimeType: APPS_MIME_TYPE, text: await readFile(new URL("../dist/widgets/weather.html", import.meta.url), "utf8"), _meta: { ui: widgetUi }, }], }), }); ``` This file path assumes the server module lives in a `server` directory, as in the quickstart. The URI identifies the resource; the reader loads the file. Supply the HTML MIME type on both the definition and its returned content. ## 2. Point the tool at the resource Add this field to your existing `tool()` definition: ```ts theme={null} _meta: { ui: { resourceUri: weatherWidget.uri } }, ``` The URI must match exactly. A tool can return ordinary JSON, which Toolgrain converts to a structured result and assistant-facing text. Use `mcpResult()` when you also need rich content or [extra widget data](/mcp-apps/security#extra-widget-data). ## 3. Register both definitions Pass the tool map and readonly resource list to your existing `createServer()` call: ```ts theme={null} const server = createServer({ name: "weather-app", version: "1.0.0", tools: { weather }, resources: [weatherWidget], }); ``` Use the server's normal [stdio or HTTP transport](/transports/overview), auth accessors, providers, and cancellation. A widget calls tools through its host; the browser does not need a second authenticated connection to the MCP endpoint. ## Tool linking and visibility | Tool `_meta.ui` field | What it controls | | - | - | | `resourceUri` | The registered widget resource to display | | `visibility: ["model", "app"]` | Assistant and widget access; also the default | | `visibility: ["model"]` | Assistant access only | | `visibility: ["app"]` | Widget access only | For example, register a filter/refresh tool that the assistant does not need to discover: ```ts theme={null} const refreshWeather = tool({ input: z.object({ city: z.string() }), _meta: { ui: { resourceUri: weatherWidget.uri, visibility: ["app"] } }, execute: ({ city }) => ({ city, temperature: 29 }), }); ``` Register it under an exposed key such as `refresh_weather`. Export that map's type to React, then call `useToolCall("refresh_weather")`. A model-visible initiating tool supplies the first widget result. The host enforces visibility. Every call still needs the server's usual authentication and application authorization. Keep registration static and provide useful assistant-facing results. Permissions and CSP go on the returned HTML's `_meta.ui`, as the `widgetUi` object above shows. See [permissions and metadata](/mcp-apps/security) and the generic [resources](/guides/resources), [tool results](/tools/results), and [authorization](/guides/authorization) guides. # Shared widget entries Source: https://toolgrain.mintlify.app/mcp-apps/shared-entries Render several tool widgets from one HTML application. Follow [Add more widgets](/mcp-apps/build) for one HTML file per resource. Use this shared-entry pattern when several tools should render the same HTML application. Each host-created widget instance has its own connection and state; this does not create one persistent dashboard across the conversation. For a separate entry, declare `tool="weather"` on its provider. For a shared entry, set `resolveTool(result, hostContext)` instead. The result notification has no required tool name, and host tool information is optional, so shared routing must be explicit. The example uses application-owned `_meta.view`: ```tsx theme={null} { if (result._meta?.view === "weather") return "shared_weather"; if (result._meta?.view === "sales") return "shared_sales"; return undefined; }}> ``` The server returns that marker through `mcpResult({ content, structuredContent, _meta: { view: "weather" } })`. Toolgrain preserves it without inventing or overwriting routing fields. A missing marker produces an explicit routing error. Expected text-only errors without a marker may use a resolver fallback or display that error state. Inside `View`, call `useToolResult()` and switch on `state.toolName` to select a component. Each component can call any app-visible tool through its own `useToolCall` hook; it is not restricted to its initiating tool. Tool visibility is enforced by the host and is not endpoint authorization. # Architecture and protocol Source: https://toolgrain.mintlify.app/project/architecture Understand package boundaries, protocol revisions, and transport lifecycle. How Toolgrain separates tool execution, protocol revisions, and transport lifecycle. Start with the [tool guide](/tools/overview) if you are building a server. ## Protocol package `@toolgrain/protocol` is a published library containing the pinned official schemas and constants, including `PROTOCOL_VERSION`, `LEGACY_PROTOCOL_VERSION`, and `SUPPORTED_PROTOCOL_VERSIONS`. Workspace code imports modern wire types such as `JSONRPCResponse` directly from it. Runtime validators stay in MCP; MCP exports server/transport interfaces without re-exporting wire definitions. Legacy wire types are available from `@toolgrain/protocol/2025-06-18`. The root `ProtocolResponse` type covers responses from both eras. It has no runtime dependencies. Generated server and transport declarations reference this package. Its compiled exports point only to `dist`, like the other packages. ## MCP server implementation Implementation responsibilities are separated: * `server.ts` composes the server; `dispatcher.ts` selects the protocol era. * `modern/` and `legacy/` own their request validation, method handling, and response shapes. * `legacy/connection.ts` owns initialization/readiness and initialization cancellation rules. * `connection.ts` owns shared transport lifecycle and writes; `pending-requests.ts` tracks cancellation. * `protocol/` owns shared envelopes, decoding, and protocol errors. * `resources/` owns fixed definitions, registration snapshots, result validation, and shared list/read handling. * `tools/definition.ts` defines the public API; `tools/registry.ts` validates and executes inputs. * `tools/schema.ts` converts schemas and metadata; `tools/adapter.ts` adapts execution. * `tools/rich-result.ts` marks explicit results; `tools/content.ts` validates rich content. * `tools/json-value.ts` checks JSON values; `tools/results.ts` normalizes outputs before either era shapes its wire result. Modern modules do not depend on legacy modules. Removing legacy support would remove its modules, schema, tests, and routing/export entries; tool definitions and shared execution would remain the same. The package supports `server/discover`, `tools/list`, and `tools/call` for modern `2026-07-28` requests carrying version and client capability metadata. Legacy clients use `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call` under `2025-06-18`. Initialization negotiates the supported legacy revision, including when the client proposes another revision. Only these two wire revisions are implemented. The connection handles each client era without changing tool definitions or requiring a server mode setting. Both revisions also support fixed resources through `resources/list`, `resources/read`, and empty `resources/templates/list`. The optional `resources` array enables the capability even when empty. Each registry is static, matches exact URIs, and shares tool request context, providers, and endpoint auth. Modern discovery lists both supported versions. Modern discovery and tool lists use `ttlMs: 0` and `cacheScope: "private"`; legacy listings omit modern result and cache fields. Tool and fixed-resource lists share stateless cursor pagination over their registration snapshots, with a configurable `listPageSize` (default `100`). Only the requested page is cloned; cursors belong to one server and list. Tool inputs must convert to JSON Schema with an object root. Conversion uses the schema's input shape, preserving transforms/defaults for execution. Invalid schemas fail at server construction with `ToolSchemaError`. Without an output schema, strings become text content; other JSON values become structured content and JSON text in modern mode. With an output schema, parsed strings also include structured content and serialized JSON text. Legacy structured content is limited to objects; arrays, null, numbers, and booleans return JSON text only. Non-JSON values fail as tool errors rather than being silently coerced. Input/output validation and handler failures return `isError: true`; malformed requests and unknown tools return protocol errors. Unexpected handler failures return generic errors and reach the server diagnostics callback; explicit public `mcpResult()` errors retain their intended content. `Transport` provides asynchronous `start(callbacks)`, `send(message)`, and `close()`. Its messages use `ProtocolResponse | ProgressNotification`, covering responses and request-scoped progress in both protocol eras. Callbacks report decoded messages, JSON parse failures, transport errors, and EOF. Adapters own byte framing and JSON parsing. Messages run independently; writes are serialized. `listen()` resolves after startup. A server permits one transport attachment, and `close()` is terminal and idempotent. Transport failures terminate the attachment and reach the optional server `onError` callback. Diagnostics do not write to stdout. Each tool adapter creates one internal registry and reuses it for all executions. Cancellation suppresses pending responses and aborts the handler's `ctx.signal`; handlers stop early only if they observe it. A request cancelled during validation never starts its handler. Responses already handed to an adapter cannot be recalled. Each execution owns a bound progress reporter. It validates and snapshots active updates, serializes delivery, drains accepted writes before the final response, and stops accepting reports on completion or cancellation. `ToolContext` exposes only `reportProgress(update)`; the dispatcher receives its request-scoped delivery callback explicitly. Direct contexts and callers without a channel use a no-op. HTTP opens SSE lazily on the first progress notification and retains authorization until final delivery or cancellation. Node owns stream conversion and backpressure. Both complete upstream schemas are vendored unchanged at commit `271ecc9accafdd9b83a3c869fa67c22953b2af80`, with checksum/provenance and its license under the `@toolgrain/protocol` workspace, in sibling revision folders `packages/protocol/src/vendor/2026-07-28/` and `packages/protocol/src/vendor/2025-06-18/`. Builds retain those files. Updates are explicit; there is no build-time download or MCP SDK dependency. The `@toolgrain/react` package implements the Apps iframe lifecycle and typed React bindings, with fixed HTML resources supplied by the server. Its browser connection is internal. The [MCP Apps guide](/mcp-apps/overview) describes the 0.3.0 APIs; [capability coverage](/mcp-apps/capabilities#react-protocol-support) separates wire declarations from implemented React actions. Resource templates, prompts, multi-round-trip input-required results, subscriptions, and additional extensions remain future work. [The release guide](/project/releases) describes Changesets records, generated package changelogs, and automated Release PRs. # Changelogs Source: https://toolgrain.mintlify.app/project/changelog Find package-specific changes, GitHub releases, and historical release notes. All seven library workspaces share a version through a fixed Changesets group. Release notes live in each package's changelog and in its package-scoped GitHub release. Use matching Toolgrain versions in your application. | Package | Changelog | | - | - | | `@toolgrain/mcp` | [Tool authoring and server changes](https://github.com/keshavkatwe/toolgrain/blob/main/packages/mcp/CHANGELOG.md) | | `@toolgrain/node` | [Node transport changes](https://github.com/keshavkatwe/toolgrain/blob/main/packages/node/CHANGELOG.md) | | `@toolgrain/http` | [Web handler changes](https://github.com/keshavkatwe/toolgrain/blob/main/packages/http/CHANGELOG.md) | | `@toolgrain/jwt` | [JWT integration changes](https://github.com/keshavkatwe/toolgrain/blob/main/packages/jwt/CHANGELOG.md) | | `@toolgrain/clerk` | [Clerk integration changes](https://github.com/keshavkatwe/toolgrain/blob/main/packages/clerk/CHANGELOG.md) | | `@toolgrain/protocol` | [Protocol package changes](https://github.com/keshavkatwe/toolgrain/blob/main/packages/protocol/CHANGELOG.md) | | `@toolgrain/react` | [React widget changes](https://github.com/keshavkatwe/toolgrain/blob/main/packages/react/CHANGELOG.md) | Browse [GitHub releases](https://github.com/keshavkatwe/toolgrain/releases) for published package tags. The repository's [historical changelog](https://github.com/keshavkatwe/toolgrain/blob/main/CHANGELOG.md) preserves RC0 and initial 0.1.0 notes; it is no longer the shared release log. See [versioning and releases](/project/releases) to contribute release notes or understand verification and publication. # Contributing Source: https://toolgrain.mintlify.app/project/contributing Report an issue, prepare a focused change, and verify your pull request. Toolgrain welcomes bug reports, documentation improvements, and focused changes. Start with the repository's [contribution policy](https://github.com/keshavkatwe/toolgrain/blob/main/.github/CONTRIBUTING.md) and [Code of Conduct](https://github.com/keshavkatwe/toolgrain/blob/main/.github/CODE_OF_CONDUCT.md). Report security vulnerabilities privately using the [security policy](https://github.com/keshavkatwe/toolgrain/blob/main/.github/SECURITY.md). ## Propose a change Search [existing issues](https://github.com/keshavkatwe/toolgrain/issues) first. For a bug, include a minimal reproduction, package/runtime versions, and expected versus actual behavior. Discuss feature and API changes in an issue before investing in a large implementation. The [roadmap](https://github.com/keshavkatwe/toolgrain/blob/main/ROADMAP.md) separates implemented capabilities from proposals. ## Prepare a pull request Fork the repository for an external contribution and create a branch before editing. Use Node.js 24.20.0 or a newer supported 24.x release and the repository's pinned Bun 1.3.14 package manager. ```bash theme={null} bun install --frozen-lockfile bun run build bun run check bun run check-types ``` Keep changes focused. Include documentation and tests when behavior changes, preserve upstream notices, and keep generated reports out of the diff. Follow [development and verification](/project/development) for the checks appropriate to your change and [architecture](/project/architecture) for package boundaries. ## Improve the documentation The Mintlify site lives in `docs/`. Edit its MDX pages and navigation in `docs/docs.json`. With the Mintlify CLI installed, run from the repository root: ```bash theme={null} cd docs mint dev ``` Validate with `mint validate` and `mint broken-links` from that directory, then `bun run check` from the repository root. Test changed commands against supported runtimes and review desktop/mobile rendering. Preserve dated compatibility evidence and distinguish it from current support commitments. The site uses Mint's native appearance with Toolgrain artwork and approved accent colors. Markdown forwarding pages preserve existing GitHub guide URLs; edit the linked MDX guide instead of creating a second copy. ## Record release intent Published-library changes, including packaged READMEs, need a Changeset. Repository-only changes use an empty record. Do not manually bump versions or edit generated package changelogs. ```bash theme={null} bun run changeset bun run release:status ``` During `0.x`, compatible fixes use patch records; features and breaking changes use minor records. Publication uses a separately reviewed Changesets Release PR. See [releases](/project/releases) for the current automated workflow and recovery. Explain the problem, resulting behavior, and validation in your PR. CI must pass before merge. Toolgrain-owned contributions use the repository's MIT license; third-party material retains its upstream terms. # Development and verification Source: https://toolgrain.mintlify.app/project/development Set up the repository and choose the right development and CI checks. Use this guide when changing Toolgrain itself. To build an application, start with the [quickstart](https://github.com/keshavkatwe/toolgrain/blob/main/README.md#quickstart) and [examples](/examples). Read [CONTRIBUTING](https://github.com/keshavkatwe/toolgrain/blob/main/.github/CONTRIBUTING.md) before opening a pull request. ## Set up the repository Use Node.js 24.20.0 or a newer supported 24.x release, and Bun **1.3.14** for repository tooling. The Bun tooling pin is separate from the supported application runtime, which starts at **1.4.4**. See the [support policy](/project/support-policy) for all supported versions. ```sh theme={null} git clone https://github.com/keshavkatwe/toolgrain.git cd toolgrain bun install --frozen-lockfile bun run build ``` Create a branch before editing. Root commands orchestrate workspaces through Turborepo; packages compile ESM and declarations with TypeScript. Public exports point to `dist`, so build before running examples or importing workspace packages. ## Develop with an MCP client Use two terminals from the repository root: ```sh theme={null} # Terminal 1: library watch builds and example development servers. bun run dev # Terminal 2: Inspector starts the compiled stdio example. bun run --cwd apps/stdio-example inspect ``` Root `dev` runs every library watcher and example development server, with concurrency 16. Initial library builds run in dependency order. Framework examples use their native development commands. Individual workspace commands start only that workspace; see the [example index](/examples) for ports and scripts. After a successful rebuild, disconnect and reconnect in Inspector to start a fresh server using the updated compiled files. Keep application diagnostics on stderr: stdout belongs to MCP. Inspector is a separate launcher, outside the watch task. ## Choose the relevant checks | Command | What it checks | | - | - | | `bun run check` | Root Biome formatting, lint, and imports | | `bun run check-types` | Workspace TypeScript checks | | `bun run test` | Library tests without coverage | | `bun run test:coverage` | Library tests with coverage thresholds and protocol integrity | | `bun run test:examples` | Real-process example integration tests | | `bun run build` | Compiled library exports and example builds | | `bun run test:package` | Compiled imports, declarations, and fresh packed consumers | | `bun run test:size` | Archive size, file inventory, and required legal/debugging files | | `bun run test:audit` | Lockfile-wide dependency advisories | | `bun run test:ci` | Repository verification and report-generation tests | | `bun run test:docs` | MDX syntax, frontmatter, navigation, local links/anchors, and documentation assets | | `bun run release:check` | Manifest and Bun workspace version alignment | Run checks that cover the change. API, transport, and packaging changes need the corresponding runtime and compiled-consumer checks. Documentation-only changes need working links, accurate examples, and formatting; packaged README changes also need archive-size checks. CI selects the applicable checks from the actual Git diff; unknown changes and unavailable history retain the full baseline. Document package-entrypoint exports and the fields, overloads, and callbacks consumers encounter through them with JSDoc. Explain defaults, validation, cancellation, and resource ownership where relevant. Internal module exports and type machinery do not need API JSDoc; keep implementation comments focused on non-obvious behavior. Check emitted declarations and IDE hovers, including inferred accessor results. Keep vendored protocol schemas unchanged. Inline documentation ships with packages, so check archive sizes after adding it. Biome is configured once at the root. `bun run check:fix` and `bun run format` write formatting changes; keep unrelated files out of your pull request. ## Find the right workspace | Location | Responsibility | | - | - | | `packages/mcp` | Tool API, validation, context, auth contracts, and protocol dispatch | | `packages/protocol` | Pinned upstream wire definitions and provenance | | `packages/http` | Shared HTTP behavior and Web handlers | | `packages/node` | Stdio, Node HTTP adapters, and managed listener | | `packages/jwt`, `packages/clerk` | Endpoint authorization integrations | | `packages/react` | Native MCP Apps browser lifecycle and typed React hooks | | `packages/repo-tools` | Unpublished build, test, package, and release verification | | `apps` | Independent runnable examples and their integration tests | | `docs` | Public usage, compatibility, support, and maintainer guides | | `brand` | Approved artwork, tokens, sources, and licensing | Keep tests and fixtures alongside the behavior they verify. Repository tooling, examples, and legal/provenance files are part of the reproducible public source; builds do not require a private repository. See [architecture](/project/architecture) for internal boundaries and [AGENTS](https://github.com/keshavkatwe/toolgrain/blob/main/AGENTS.md) for contributor invariants. ## Record release intent Use `bun run changeset` for changes to published libraries, including their packaged READMEs. Use `bun run changeset --empty` for repository-only work. `bun run release:status` previews the plan without changing versions. Follow the [release guide](/project/releases); versioning and publication belong to reviewed Release PRs. ## Continuous integration Pull requests always report `Package checks` and `Support checks`. Both use the same conservative change classifier: | Changed files | Required work | | - | - | | Documentation, artwork, contributor templates, or Changeset records only | Formatting, version alignment, and the lockfile audit; site sources and artwork also trigger `test:docs` | | Packaged README, changelog, license/notice, or editorial package metadata | The checks above, library builds, archive contents/sizes, and fresh npm/Node runtime consumers | | Runtime source, examples, dependencies/lockfile, package exports/engines, verification tooling, workflows, or unknown paths | Complete baseline and supported runtime/platform checks | Only `description`, `homepage`, and `keywords` qualify as editorial manifest changes. Mixed changes take the strongest profile. Renames consider both paths. Manual and release verification always request the complete baseline. `test:docs` compiles MDX without evaluating page JavaScript and checks required frontmatter, navigation coverage, literal local links/anchors, and assets. It does not build Mintlify's rendered site, execute examples, evaluate dynamic URLs, or fetch external links. Keep the Mintlify validation and visual review described in the [documentation instructions](https://github.com/keshavkatwe/toolgrain/blob/main/docs/README.md). The complete baseline retains type checks, 95% library coverage, example smoke tests, builds, package imports/declarations, fresh consumers, sizes, audits, and repository-tooling tests on Node 24.20.0 and Bun 1.3.14. The support workflow runs Node and Bun functional consumers on Linux, macOS, and Windows. Compiler checks run on Linux: npm declarations stay in the baseline; Bun installations check minimum/development compilers with minimum/development Zod in separate jobs. On `main`, the publication workflow chooses the release mode and owns the checks. Ordinary changes call the scoped baseline/support workflows. Publication calls complete release verification instead, including intermediate TypeScript and stable dependency drift checks, so a release commit does not start a second standalone baseline and platform matrix. Node 26 and prerelease probes run only on the weekly schedule and manual verification runs. See the [support matrix](/project/support-policy#required-ci). MCP package verification reuses its compiled consumer and runtime fixtures in isolated temporary directories. It checks TypeScript 5.5.4 and the development compiler against both Zod 4.6.6 and the development Zod version, including Classic and Mini inference and rejected definitions. Runtime checks run once per Zod version under Node with source maps enabled and check a TypeScript stack location. The isolated MCP copy includes its sources. Pinned compatibility dependencies are development tooling; verification requires no additional downloads or workspace dependency changes. Root `bun run test:package` also schedules an uncached clean installation task after the seven library package checks. Turbo flags such as `--filter`, `--force`, and `--dry=json` retain their normal behavior. A package filter that excludes the root excludes this installation task, too; dry runs perform no installations. The check packs all seven libraries with Bun and serves their unchanged archives through a temporary loopback registry scoped to `@toolgrain`. Seven fresh npm consumers each install one library as their only direct Toolgrain dependency, letting npm resolve its declared dependencies and versions. Each imports the installed library and checks its declaration fixture with both minimum and development TypeScript, with strict mode and `skipLibCheck: false`. This catches dependencies hidden by installing every library together. A separate full consumer exercises both protocol revisions over stdio, Web HTTP, Node HTTP, and the managed HTTP transport, including input validation, rich results, and a context provider. JWT and Clerk initialize with test configuration; signed-token and opaque-token verification uses offline responses. Both eras also exercise stdio cancellation and HTTP disconnects. Client-requested progress is checked over stdio and Web/Node HTTP, including ordered fractional updates, final responses, SSE cancellation, and shutdown while a final SSE write is blocked. These flows run in the supported Node/Bun matrix and post-publication consumers. No live credentials or external authorization calls are used. The default check uses npm and Node and retains all verification. Internal `clean-install --checks=runtime` jobs omit compiler installations and declaration checks, transpile the same shared fixture with the pinned minimum compiler, and run isolated imports and all functional tests. `--checks=types` checks installed declarations without repeating functional flows. Both modes retain fresh, isolated installs and dependency-tree inspection. Reports record the selected checks, installer, runtime, and platform. Node source-map verification remains required in the full package baseline. Post-publication consumers retain the default complete checks under both npm/Node and Bun. This check needs npm, Bun, tar, registry access for external dependencies, and loopback access. Zod and Node types default to development versions; declarations check TypeScript 5.5.4 and the development compiler. Weekly probes can select another compiler and current Zod 4. All consumers share disposable package-manager caches. Workspace links and unresolved local runtime dependencies are rejected. Temporary files and listeners are cleaned up; a pass/fail report is saved to `reports/clean-install.json` in the existing CI artifact. After building, run just this check with `bun run test:clean-install` or `node packages/repo-tools/src/cli.mjs clean-install`. Nothing is published. ### Coverage checks `bun run test:coverage` runs through Turborepo, building each workspace before its tests. Runtime libraries use Vitest V8 coverage over every `src/**/*.ts` file, including files not imported by tests. Thresholds apply separately to statements, branches, functions, and lines in each package: 95% for MCP, Node, HTTP, JWT, Clerk, and React. A test failure or missed threshold fails CI. Protocol runs its vendored-schema integrity test without instrumenting upstream code. Examples run their real-process integration tests through `bun run test:examples`, separately from library coverage. They have no coverage instrumentation or floors. Type-only and re-export-only modules have no executable statements to measure. Reports are written to each measured package's `coverage/` directory: terminal summary, HTML (`coverage/index.html`), LCOV, and JSON summary. Turbo caches and restores these reports using `outputs: ["coverage/**"]`. CI uploads available reports as the `test-and-coverage-reports` artifact, including after test failures, for 14 days. Ordinary `bun run test` remains available without instrumentation. Reports are generated even when tests fail (`reportOnFailure: true`). The 95% floors leave room for defensive paths without requiring contrived tests. Coverage measures executed code, not assertion quality or complete behavior. CI also writes JSON test results for every workspace and a combined Actions summary showing check outcomes, failed tests, and coverage against thresholds. Independent test suites continue after another suite fails. The same report is posted as a PR comment for branches in this repository by a separate job with PR write permission; test execution retains read-only permissions. Fork PRs use the Actions summary and downloadable artifact. Reports link to the run logs. ### Package size and dependency auditing `bun run test:size` builds and checks the seven library packages through Turbo. Each check packs the workspace with Bun 1.3.14 into a temporary directory, without running lifecycle scripts or publishing anything. It measures compressed tarball bytes, unpacked file bytes, and file count, and writes the complete file inventory and result to `packages//reports/size.json`. Runtime dependencies are not included in these sizes. Required protocol schemas, licenses, and provenance remain included. `package-size.config.json` sets a packed and unpacked byte budget for each library. Initial budgets allow approximately 20% growth above the current build, rounded up to KiB. Either exceeded budget fails CI. The archive must retain every declared export target, every compiled JavaScript/declaration file in `dist`, and the protocol's schemas, licenses, and provenance explicitly listed in the config. Missing required files and unexpected package files fail the check. Intentional growth requires reviewing and updating the relevant budget. Size checks run uncached to inspect the actual package contents on every run. They depend on the libraries' own builds and still run when an unrelated application build fails. MCP's `sourceMaps` size policy additionally requires JavaScript maps, declaration maps, and the TypeScript sources in the archive. Verification rejects malformed maps, missing or incorrect source targets, and missing mapping comments. Packaged sources are limited to existing `src/**/*.ts` files; other libraries retain their existing restrictions. MCP's budgets are 115 KiB packed and 455 KiB unpacked. These limits include fixed resources, request-scoped progress, and typed content helpers, along with API documentation, package metadata, README, changelog, sources, and maps. Every library archive must include its package-root README and LICENSE; protocol and Clerk also require their package-root NOTICE files. Size budgets include the required legal notices. `bun run test:audit` queries Bun's advisory service for the complete `bun.lock`. It runs outside Turbo caching because advisories change independently of Git. High or critical findings fail the check, as do connection failures and malformed scanner responses. The report is written to `reports/audit.json`; it does not claim to attribute advisories to individual workspaces. # Licensing and protocol provenance Source: https://toolgrain.mintlify.app/project/licensing Locate Toolgrain licenses, upstream protocol terms, and integration notices. Toolgrain-owned code is MIT licensed with copyright attribution to Keshav Katwe. The repository and package-local license files preserve the grant. Vendored upstream material retains its own unchanged terms. ## Protocol schemas `@toolgrain/protocol` vendors the TypeScript and JSON schemas for both supported revisions from pinned upstream commit `271ecc9accafdd9b83a3c869fa67c22953b2af80`. Each revision has provenance, integrity checksums, and upstream license artifacts. The package's root LICENSE/NOTICE explain its mixed contents; its manifest uses `SEE LICENSE IN LICENSE`. TypeScript schemas and provenance are distributed with compiled outputs. The JSON schemas are test-only conformance fixtures and are not copied to `dist`. Upstream updates require separate review and renewed interoperability verification. Do not modify or format vendored sources as part of an unrelated change. ## Integration notices The Clerk package includes a NOTICE preserving Svix and Deno MIT attributions associated with `standardwebhooks@1.1.1`. Its npm archive omitted upstream parent-directory license/source attribution; Toolgrain preserves the exact release's notices and provenance. Keep the NOTICE in the Clerk archive and renew the review when updating that dependency. ## Documentation starter The documentation setup includes material from Mintlify's starter. Its MIT license, copyright 2026 Mintlify, is preserved unchanged in the [starter notice](https://github.com/keshavkatwe/toolgrain/blob/main/docs/notices/mintlify-starter.txt). Toolgrain-owned code and documentation use the repository's root MIT license. ## Brand and fonts The approved Toolgrain mark, outlined wordmarks, lockups, shared tokens, and usage guide live in [brand/](https://github.com/keshavkatwe/toolgrain/tree/main/brand). The bundled Manrope source retains its SIL Open Font License and FONTLOG there. This documentation site uses Mint's default typography and outlined logo exports; it does not bundle the brand font. Outlined exports do not require a font installation. Consult the actual [root license](https://github.com/keshavkatwe/toolgrain/blob/main/LICENSE), package license/notice files, and dependency terms when redistributing artifacts. # Versioning and releases Source: https://toolgrain.mintlify.app/project/releases Changesets release planning, automated publication, verification, and recovery. Toolgrain versions its seven library workspaces as one fixed group. Stable publication uses npm's `latest` tag. Check [npm](https://www.npmjs.com/package/@toolgrain/mcp) for the current version and [package releases](https://github.com/keshavkatwe/toolgrain/releases) for release notes. The historical [v0.1.0 release](https://github.com/keshavkatwe/toolgrain/releases/tag/v0.1.0) and [RC0 prerelease](https://github.com/keshavkatwe/toolgrain/releases/tag/v0.1.0-rc.0) remain available. `next` still points to RC0. Changesets automation is active on `main`, with package-local changelogs and package-scoped GitHub releases. The publication workflow owns main-branch verification. It calls ordinary scoped CI/support checks when no publication is planned, and complete release verification when publishing. This avoids duplicate baseline/platform runs on release commits. The `publish.yml` filename, `npm` environment, and trusted-publisher bindings stay the same. ## Current release status **Toolgrain 0.3.0 was published on November 8, 2026 for all seven libraries under npm's `latest` tag.** [Release PR #63](https://github.com/keshavkatwe/toolgrain/pull/63) merged as commit [`d067bbb`](https://github.com/keshavkatwe/toolgrain/commit/d067bbb8d1710b232d026d1f3754c9b0fd112d4f). The release includes progress, fixed resources, MCP Apps/React, host actions, typed rich-content helpers, and the Vite walkthrough. The [release run](https://github.com/keshavkatwe/toolgrain/actions/runs/42451243089) passed the full release matrix, including supported TypeScript versions and stable dependency drift, before publishing. All seven downloaded npm archives matched the verified build artifacts. Registry integrity and fresh Node/Bun consumer checks passed. All seven versions include npm provenance and package-scoped GitHub releases. Install matching Toolgrain versions using the guides' npm commands. Exact build and host test versions remain in the [Apps compatibility record](/mcp-apps/compatibility); publication checks do not extend the recorded live-host coverage. The existing prerelease tags are unchanged: all seven `alpha` tags remain `0.3.0-alpha.3`, and the six established libraries' `next` tags retain `0.1.0-rc.0`. Registry values were checked on November 8, 2026. ## Verified automated release The first complete automated cycle published **0.1.1** for all six libraries on 2026-10-26. [Release PR #37](https://github.com/keshavkatwe/toolgrain/pull/37) merged as commit `fed5a82826e66b485bad7cdb86fbc2238ae7a3e4`. The [publication run](https://github.com/keshavkatwe/toolgrain/actions/runs/40274053979) passed release verification, the supported runtime/platform matrix, archive packing, npm publication, package tags/releases, and registry integrity checks. Both **Published node consumers** and **Published bun consumers** passed against the public packages after publication. These results verify this release cycle; client-flow coverage remains limited to the [compatibility reports](/compatibility/protocol). ## Record a change Run `bun run changeset` for a user-facing library change. Select affected libraries, a bump type, and write release notes that explain the behavior and any migration steps. Include the Markdown record with the implementation when committing is authorized. Use `bun run changeset --empty` for repository-only changes that need no library release. Release PR versioning consumes all Changeset records. Keep that state when fixing a versioned Release PR: the pinned action selects no publication when only empty records remain. Consume an empty record during versioning rather than carrying a fresh one into the release merge. The pinned Changesets CLI 3.0.3 selects versions and updates dependencies. The seven library workspaces form one explicit fixed group in `.changeset/config.json` and share a version; their manifests are the source of truth. Examples and repository tooling are unpublished npm workspaces and are ignored by Changesets. During `0.x`, compatible fixes use patch records, while features and breaking changes use minor records. From `1.0`, follow semantic versioning. The [support policy](/project/support-policy), including minimum increases and removal notices, still applies. `bun run release:status` previews the pending plan. Package-local `CHANGELOG.md` files are generated by Changesets and become the source for release notes. Review their summaries and migration guidance in the Release PR. The root [CHANGELOG.md](https://github.com/keshavkatwe/toolgrain/blob/main/CHANGELOG.md) preserves the historical RC0/0.1.0 notes; it is no longer a second release ledger that must be edited for each change. ## Plan a release Develop each feature on its own branch and reviewed PR, with tests, documentation, and a Changeset. Choose a small release scope: one feature or a few related features that can be accepted together. Use one temporary `prerelease/X.Y` branch to assemble the selected commits and prepare test packages. | Stage | Example version | Purpose | | - | - | - | | Alpha | `0.3.0-alpha.0` | Test selected features while the release is still being built; add reviewed features in later alphas | | Beta | `0.3.0-beta.2` | All planned features are included and APIs are settled; focus on fixes and combined application testing | | RC | `0.3.0-rc.3` | Final candidate for stable publication; repeat acceptance after any changes | | Stable | `0.3.0` | Accepted implementation, published through the reviewed stable Release PR | All libraries in the fixed group share each version. Alpha, beta, and RC use matching npm tags; stable `latest` and historical `next` stay unchanged during prerelease testing. Every stage retains the full release verification and post-publication checks. The pinned Changesets CLI continues its numeric counter across stages: for example, `alpha.0` → `alpha.1` → `beta.2` → `rc.3`. Use the version it generates. Freeze the feature scope at beta. Adding a feature after that point reopens the scope and requires renewed combined testing. An individual feature's acceptance does not establish acceptance of the combined release. ### Where to make changes Make implementation fixes in the original feature branch and PR, then bring the new commits into the same series branch and publish a new prerelease version. Only release preparation, such as versions, generated changelogs, prerelease state, and manifest tags, belongs directly on the series branch. Keep feature PRs open until acceptance so their fixes can reach `main` through ordinary review. For example, fix progress on its original feature branch, bring that commit into `prerelease/0.3`, and publish the next `0.3.0-alpha.N`. Alpha is a release stage, not another required branch. The same series branch later produces beta and RC. Install exact published versions when recording test results. After RC acceptance and explicit stable-release authorization, merge the approved feature PRs into `main` and review the ordinary Changesets Release PR. Verify that the stable implementation matches the accepted RC. Keep candidate metadata off `main`; do not merge the series branch into it. Agreement on the strategy does not authorize publication, feature merges, or a stable release. Each prerelease requires confirmation of its prepared version and full commit SHA. The reviewed stable Release PR remains the stable publication gate. ## Automated release PR and publication The `npm publication` workflow runs on pushes to `main`, using Changesets Action v2.1.2's native `select-mode`, `version`, `pack`, and `publish` subactions. Its commit is pinned; CLI and Action upgrades must be reviewed together. 1. Merge an ordinary reviewed change with its changeset. Changesets creates or updates **Release Toolgrain packages** on `changeset-release/main`. 2. The bot runs `bun run release:version`, consuming records, updating all library versions/dependencies and package changelogs, and synchronizing Bun workspace versions. Review that diff and the CI results. With `GITHUB_TOKEN`, GitHub can require a maintainer to **Approve workflows to run** for bot-created PR runs; approve those runs during review. No personal token is required. 3. Merge the reviewed Release PR when ready to publish. **This merge approves automatic npm publication, package tags, and GitHub releases.** The workflow does not auto-merge the PR. Bot version commits/PRs are authorized by this automation policy; local agent commits still need an explicit user request. 4. On the merged main commit, the workflow runs Release verification: baseline, the full supported runtime/platform matrix, intermediate TypeScript versions, and stable dependency drift. Supported failures block publication; Node 26 and prerelease probes remain informational. 5. A separate job builds the libraries, checks contents and size budgets, and uses Changesets to create packed archives and its publish-plan artifact. Only the publish job gets OIDC permission. It publishes those archives to npm under `latest`, pushes package tags, and creates package-scoped GitHub releases from their package changelogs. Names follow `@toolgrain/mcp@0.1.1`, for example. 6. Post-publication checks verify all library `latest` tags in full and installer npm metadata, registry integrity, and downloaded archive bytes against the packed artifact. Fresh npm/Node and Bun consumers then check all library imports, minimum/current declarations, and the stdio/HTTP runtime flows. Reports are retained as workflow artifacts. A post-publication failure needs investigation; npm publication cannot be rolled back by a failed check. No local version bump, manual npm publish, combined `vX.Y.Z` tag, or separate GitHub release command is needed for this flow. The existing `v0.1.0` and RC0 release records are preserved. Repository-only changes use empty changesets and do not select a library release. User-facing changesets create or update the next automated Release PR. ## npm publication setup The existing published libraries use public access, the explicit npmjs registry, and stable `latest` configuration. The workflow retains filename `publish.yml`, environment `npm`, and the seven validated trusted-publisher bindings for `keshavkatwe/toolgrain`. No npm token secret or local login is required for those bindings. Stable publication uses main; prereleases require the exact active series branch to be allowed as described below. The `@toolgrain/react` package participates in version alignment and verification. Its first real publication was `0.3.0-alpha.2`, using the verified archive and maintainer authentication; that initial publication has no automatic npm CI provenance. The [combined publication run](https://github.com/keshavkatwe/toolgrain/actions/runs/42244638853) published the other six packages and verified all seven archives plus fresh Node/Bun consumers. At that time, the prerelease tooling preserved stable `latest=0.2.0` for the six established packages. npm assigned React's initial `latest` to the alpha and rejected removing that tag. Stable 0.3.0 replaced that initial React `latest` value. React's reviewed trusted-publisher binding completed its first CI/OIDC publication in the [November 7, 2026 run](https://github.com/keshavkatwe/toolgrain/actions/runs/42393275595). All seven `0.3.0-alpha.3` archives matched the approved build, and fresh Node/Bun consumers passed. React's provenance identifies the approved source commit. Do not republish an existing version or create a placeholder to exercise automation. Candidate state remains on its series branch. The publication workflow, `npm` environment, and publisher bindings are unchanged by documentation cleanup. The reviewed Release PR is the stable publication gate. A prerelease needs an explicitly allowed, exact prerelease branch as described below; do not broaden this to all branches. GitHub Actions must be allowed to create pull requests in repository settings (**Actions → General → Allow GitHub Actions to create and approve pull requests**). Keep default workflow permissions read-only. The version job requests pull-request write access; the reused baseline retains its PR-report permission. The workflow never approves reviews itself. External workflow Actions are pinned to full upstream commit SHAs. When updating an Action, verify the new commit in its canonical repository and update every reference, including composite actions. The repository's Actions allowlist must permit the new pin before workflows use it. Enable the full-SHA policy only after all active workflow branches use pinned references. The active tag ruleset blocks updates and deletions for every tag, without bypass actors. New release tags can still be created by the publication workflow. The source repository is public, so publications automatically request npm provenance. RC0 and 0.1.0 were published without provenance while the source was private. All six trusted publishers completed their first successful OIDC publication for 0.1.0; a new or replacement binding must complete its first successful publish within npm's two-day validation window. Changesets does not currently support Bun natively. The workflow-only npm adapter preserves the native planner, packed-artifact format, publishing order, tag reporting, and GitHub release handling. It uses Bun 1.3.14 to pack archives with rewritten `workspace:*` dependencies. Registry reads and npm 11.21.1 archive publication run outside the checkout, where npm does not encounter the repository's intentional Bun `devEngines` requirement. Archive lifecycle scripts are disabled. Ordinary development continues to use Bun. `release:version` retains the existing narrow Bun workaround: Bun 1.3.14 leaves stale workspace versions during lockfile-only installs, and packing reads them. The helper synchronizes only the library version fields, preserving external resolutions. `bun run release:check [--version X.Y.Z]` checks manifest/lock alignment. It does not select versions or write changelogs. ## Failures and recovery Publication across the seven packages is not atomic. Inspect the run, its plan/archive artifacts, npm versions/tags, and GitHub tags/releases before recovery. Never unpublish or replace an existing version. The manual **Run workflow** action on main runs the same planner and all verification gates; it does not bypass them. Prefer a fresh run after checking partial state so Changesets can replan around already-published versions, rather than replaying a stale packed publish job. Existing remote tags with missing GitHub releases need explicit inspection and repair; the native action does not guarantee recreating missing release records. A maintainer can still dispatch **Release verification** on main with an expected version without publishing. Local preparation can use `release:status`, `release:version`, and `release:check` in a disposable checkout; do not version main manually alongside the bot's Release PR. ## Verify a release candidate before stable publication Stable publication uses the reviewed Release PR on `main`. Prerelease publication is a manual dispatch from one protected branch per release series, for example `prerelease/0.3`. All libraries in the fixed group share each prerelease version, such as `0.3.0-alpha.0`, and publish under its matching `alpha`, `beta`, or `rc` tag. Stable `latest` and historical `next` stay unchanged. Keep the `publish.yml` filename, `npm` environment, and existing trusted-publisher bindings. In the environment's deployment-branch settings, allow `main` and only the exact active series branch. Restrict updates to trusted maintainers and review changes to publication code. A feature branch or a per-version branch such as `prerelease/0.3.0-alpha.0` cannot publish through this prerelease path. ### Prepare and publish a candidate 1. Review the release infrastructure independently of the feature. Keep the selected feature PRs in draft while preparing and testing prereleases. 2. Create the series branch from the reviewed infrastructure plus the selected feature commits. For early testing, run `bun run changeset pre enter alpha`, then `bun run release:version`. Set `publishConfig.tag` to `alpha` in all library manifests. Changesets selects versions and changelogs; `release:version` aligns the Bun workspace metadata. Commit the prepared state when authorized. 3. Run the full local checks, push the series branch, and record its full commit SHA and version. Manually dispatch **npm publication** on that branch with both `version` and `expected_sha`. For example: ```sh theme={null} gh workflow run publish.yml --ref prerelease/0.3 \ -f version=0.3.0-alpha.0 -f expected_sha=FULL_PREPARED_COMMIT_SHA ``` 4. The workflow rejects missing or mismatched inputs, the wrong release series, a stable version on a prerelease branch, and any mismatch between the version's stage, Changesets prerelease tag, and all library manifest tags. Pushes alone do not publish. The run uses the exact triggering commit so npm provenance identifies the verified candidate. Moving the branch does not change an already-dispatched run's source; an expected-SHA mismatch fails the run. 5. The existing complete release verification runs before packing. Publication uses those packed artifacts, validates their package/version/tag plan, and retains a `publication-manifest` artifact containing the source SHA, workflow run, and package archive identities. Post-publication checks verify all library versions under the selected tag, unchanged stable `latest` in both npm metadata formats, archive integrity, and fresh Node/Bun consumers. 6. Install the exact candidate in the real application. Record the requirement, installed version, source SHA, workflow run, and observed result on the feature PRs. For the OAuth change, check automatic scope selection, fresh CIMD/DCR authorization and consent, refresh/retry, tool access, and removal of the response-enrichment workaround. Local token tests do not replace these checks. The manual dispatch approves only the specified prerelease. For ordinary manual stable recovery on `main`, leave both prerelease inputs blank; supplying them on main is rejected. ### Move from alpha to beta or RC Use the same `prerelease/X.Y` branch throughout the series. To change stages, edit the `tag` in `.changeset/pre.json` to `beta` or `rc`. Version the next feature or fix Changeset with `bun run release:version`. Changing the tag alone does not advance the package versions. If no implementation Changeset is pending, use `bun run changeset` on the series branch to add a patch record that accurately describes the stage transition, then run `bun run release:version`. This release preparation record stays on the series branch and is excluded from main. Set `publishConfig.tag` in all library manifests to the same stage. Let Changesets select the versions; do not rename manifest versions or relabel an existing published archive. Review the prepared diff and dispatch with the resulting exact version and full source SHA when authorized. Each stage publishes a new immutable version under its matching tag. Other prerelease tags keep their previous versions, and `latest` remains stable. Beta requires the complete selected feature set; stable publication requires successful RC acceptance and the separately reviewed stable Release PR. ### If the published candidate fails the requirements Fix the original feature PR and add a regression test. Bring the fix and its new Changeset into the same series branch, then run `bun run release:version` again. The next candidate advances, for example, from `0.3.0-alpha.0` to `0.3.0-alpha.1` across all aligned libraries. Review the prepared diff, commit/push when authorized, and dispatch with the new version and full SHA. Repeat all publication and acceptance checks. No new release branch or environment permission is needed for each candidate. Never overwrite or unpublish the previous candidate. Its stage's npm tag moves to the new candidate after publication; `latest` remains on stable. A partial publication is not an accepted candidate: inspect all library registry versions and the original workflow's plan/artifacts before recovery. Never reuse a published candidate version for changed source. Keep the exact commit and verified artifact identities when recovering a partially published run. ### Release stable after acceptance Keep candidate version commits, `.changeset/pre.json`, consumed prerelease Changesets, and prerelease manifest tags off main. Once the final RC passes real-application acceptance and stable publication is explicitly authorized, merge the reviewed feature PRs and use the ordinary stable Changesets Release PR. Check that the stable package implementation matches the accepted candidate, allowing the intended version, internal dependency version, and changelog changes. A further runtime, external dependency, or exported-API change requires another RC. Run the full stable release checks on the exact final commit. Merging the reviewed Release PR remains stable publication approval; do not merge the RC branch or point `latest` at an RC version. Remove the series branch's environment permission when that series is complete. Do not repeat the initial 0.0.0 bootstrap used to select RC0. The stable baseline's documented client limitations remain in the [published-package verification](/compatibility/published-packages). References: [Changesets automation](https://changesets.dev/guide/automating), [Action v2.1.2](https://github.com/changesets/action/tree/v2.1.2), and [GitHub workflow triggering rules](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/trigger-a-workflow). # Runtime and dependency support Source: https://toolgrain.mintlify.app/project/support-policy Supported runtimes, TypeScript, Zod, platforms, and upgrade rules. All seven library workspaces use one fixed release group, with stable publication under npm's `latest` tag. This policy defines their runtime and dependency contract. CI configuration alone does not establish that an unrun platform has passed; releases require a green supported matrix. See the [published-package verification](/compatibility/published-packages) for recorded results. The `@toolgrain/react` package targets Toolgrain 0.3.0 or later and uses the same TypeScript/Zod consumer floors. Its initial browser integration requires React `^19.3.1`; the example pins React and React DOM 19.3.1. Server runtime floors below apply to its server/tooling integrations. Live widget compatibility is recorded separately in the [Apps acceptance notes](/mcp-apps/compatibility). ## Supported versions | Component | Contract | Verification | | - | - | - | | Node.js | 24.x from 24.20.0, for library Node integrations | Exact minimum in the full baseline; latest 24.x in packed-consumer jobs | | Bun runtime | 1.x from 1.4.4, for library Bun integrations | Minimum on Linux and latest stable 1.x on Linux, macOS, and Windows | | Repository tools | Bun 1.3.14 and Node 24.20.0 baseline | Frozen lockfile; the Bun development pin is independent of consumer runtime support | | TypeScript | 5.5.4 minimum, with strict mode | Minimum and development compiler for each installed library; MCP/JWT/Clerk also cross minimum/current Zod | | Zod | `^4.6.6`, Classic and Mini | Minimum 4.6.6 and development version; weekly current 4.x | | Modules | ESM, compiled `dist` exports and declarations | Package exports, isolated imports, and declaration consumers; CommonJS/node10 resolution are unsupported | | Operating systems | Linux, macOS, Windows on the architectures exercised by CI | Real packed consumers, stdio subprocesses, HTTP listeners, disconnect/cancellation and cleanup; reports/logs record runtime/platform/architecture | | Installation | npm and Bun | Unchanged Bun-packed archives installed through each package manager's resolver | Node support is declared as `^24.20.0`; Bun as `>=1.4.4 <2`, in every library. The root manifest describes development requirements. It is not a substitute for published package metadata. `support-policy.json` records the approved floors and ranges; packed-install checks reject missing or inconsistent library ranges. These declarations describe each runtime separately, not a requirement to run both Node and Bun. Package engines are advisory in npm unless the consumer uses `engine-strict`; they are not a runtime guard. The initial Bun 1.3.14 runtime proposal failed the new disconnect test: its `node:http` server did not emit the response/socket close events needed to abort an in-flight handler. Bun 1.4.0 also failed the disconnect test; 1.4.4 passed it. The application runtime floor is therefore 1.4.4, while repository tooling remains pinned at 1.3.14. Earlier Bun example checks established only their tested subset, not the complete adapter contract. See [Bun 1.4's Node compatibility changes](https://bun.com/blog/bun-v1.4#nodejs-compatibility). The initial release uses a Zod floor of 4.6.6 because earlier versions are affected by [GHSA-mrhx-c7xc-m3w5](https://github.com/advisories/GHSA-mrhx-c7xc-m3w5). Strict TypeScript 5.5.4 remains the compiler minimum. Node 26 has a non-blocking preview job. Its upstream LTS transition is scheduled for 2026-10-28. Promotion requires a reviewed policy/manifest/CI change after LTS and successful verification; the date alone does not promote it. Node 24's scheduled EOL is 2028-04-30. Node 22 is outside the initial matrix; its scheduled EOL is 2027-04-30. See the [upstream Node schedule](https://github.com/nodejs/Release/blob/main/schedule.json). `@toolgrain/react` runs in an MCP Apps host's browser iframe; compatibility is limited to the [recorded host versions and transports](/mcp-apps/compatibility). This does not make the server adapters browser runtimes. Deno, Workers, other package managers, and untested OS/architecture combinations have no support commitment. Runtime-independent modules may be usable there. Framework examples retain their own pinned framework/runtime requirements; an example is not a promise to support every framework version. ## Required CI `.github/workflows/ci.yml` retains the complete Linux/Node 24.20.0 baseline for runtime, dependency, packaging-contract, verification, workflow, and unknown changes: formatting/lint, type checks, 95% coverage floors, framework examples, builds, compiled consumers, minimum Zod checks, package exports, clean installs, sizes, dependency audit, and repository-tooling tests. Manual runs and legacy `v*` tags also request the complete baseline. Documentation and artwork take a lighter formatting/audit/source-validation path. Packaged documents and editorial metadata additionally require library builds, archive contents/size checks, and fresh npm/Node functional consumers. Only `description`, `homepage`, and `keywords` can change in a light package manifest. Unknown paths, missing Git history, and mixed changes retain full verification. See the [development guide](/project/development#continuous-integration) for the profiles. `.github/workflows/support.yml` runs the supported matrix for full-profile PRs, main changes, legacy `v*` tags, weekly checks and manual runs: * Latest Node 24 on Linux, macOS and Windows with npm consumers. * Bun 1.4.4 on Linux and latest stable Bun 1.x on all three OSes with Bun consumers. * Node 26 on Linux as an explicitly non-blocking preview, on weekly/manual runs only. Each compatibility job builds libraries through Turbo's package filter and runs uncached packed-install functional verification directly. Declaration compatibility is checked once on Linux for npm and Bun installations, with minimum/development compilers, strict mode, `skipLibCheck: false`, and minimum/development Zod. Each library retains its own isolated installation and import checks on every supported runtime/platform. The functional consumer verifies both protocol eras, Web/Node HTTP, the managed listener, actual stdin/stdout, contexts, rich results, input validation, stdio cancellation, HTTP disconnects and cleanup. Auth checks cover signed RS256/ES256 JWTs, audience rejection, frozen identities, Clerk OAuth JWTs and Clerk's opaque-token path using synthetic fetch responses. No live keys, OAuth login, consent flow or provider network calls are involved. Bun runs the functional consumer suite itself, including its subprocesses. Node runs its own suite; invoking scripts through Bun alone is not runtime coverage. The existing Node source-map stack assertion remains required. On Bun 1.3.14, that assertion reports compiled JS locations; mapped TypeScript stacks are currently a Node-specific guarantee. This does not waive functional checks on Bun or alter the package's maps/sources. Every Monday, and on manual workflow dispatch, additional jobs run: * The latest patch of every TypeScript minor between the approved minimum and development compiler minor, against latest Zod 4. Registry lookup errors fail the plan instead of silently reducing coverage. * Stable upstream dependency drift within jose 6, Clerk backend 3 and Clerk shared 4, latest stable TypeScript, and latest Zod 4. Only disposable CI manifests/lockfiles change. This job must pass before a release. * A non-blocking Bun canary/TypeScript-next probe. Prereleases are not supported merely because this probe passes. The applicable stable matrix and baseline must be green before merge. Every release requires the complete supported baseline and matrix on its exact merged commit, including stable dependency drift and intermediate TypeScript checks. On main, the publication workflow calls either ordinary scoped checks or the complete release gate; standalone main CI/support runs do not duplicate it. A confirmed regression from weekly checks in a supported version also blocks release until resolved; prerelease/Node-26 preview failures are informational. No publication is performed by these workflows. New matrix check names must be selected in repository branch protection when configuring required checks; workflow files alone do not change GitHub repository settings. Require `Package checks` and `Support checks`, rather than individual matrix jobs. The support gate checks planning and every applicable supported job, rejecting failures, cancellations, and unexpected skips. An editorial skip makes no new runtime/platform claim. When adopting these scoped workflows, first let a full-profile PR produce both stable check names successfully, then replace the previous per-platform required contexts with those two gates before merging. Preserve strict up-to-date checking and the GitHub Actions app binding. No protection setting changes automatically. The manual [Release verification workflow](/project/releases#failures-and-recovery) reuses both workflows at the selected source commit, including weekly stable dependency and intermediate TypeScript checks. It does not produce candidate archives. Reports are retained as separate job artifacts with runtime/package-manager identity. Linux/macOS/Windows hosted results are required before claiming those specific combinations verified. Local runs cannot stand in for another OS. ## Upgrade and deprecation rules 1. Review dependency updates monthly; handle urgent security fixes sooner. Keep direct runtime/development dependencies exactly pinned and commit a reviewed lockfile. Weekly floating probes never change normal installation policy. 2. Runtime dependencies, especially jose and Clerk, must pass the supported runtime and declaration floors, auth regressions, exports and packed installs. Development compiler/tool upgrades must also preserve emitted declaration compatibility. A transitive requirement increase counts too. 3. Add new runtime/dependency majors explicitly after stable upstream release and successful CI/interoperability checks relevant to the change. Do not infer support from a broad `>=` range or a successful preview job. 4. Raising a Node, Bun, TypeScript or Zod minimum, dropping a supported major, or removing public behavior is a breaking change: use a minor release during `0.x` and a major release from `1.0`. Updating the development pin alone is not a consumer minimum increase. 5. Announce removals at least 90 days and one published release beforehand, whichever is longer, with a migration path and affected package versions. A documented security emergency may shorten notice; never hide the change. The initial unpublished baseline does not need a deprecation period. 6. Review runtime retirement around upstream EOL. An EOL date does not silently change already-published package ranges or authorize indefinite old-branch maintenance. State the last supported Toolgrain release when retiring a target. 7. Protocol revisions and vendored schemas require their own explicit review, provenance/checksum updates, conformance and interoperability verification. Dependency automation must not rewrite them. Renew client checks for protocol, transport/auth behavior changes and new runtime-major support. The existing TypeScript/Zod floors agree with [Zod's documented TypeScript requirement](https://zod.dev/#requirements). [Bun's Node compatibility documentation](https://bun.com/docs/runtime/nodejs-compat) describes upstream API coverage; Toolgrain's own matrix determines its promises. [npm documents engines and development engines separately](https://docs.npmjs.com/cli/v11/configuring-npm/package-json/#engines). # Quickstart Source: https://toolgrain.mintlify.app/quickstart Build a typed MCP tool and call it with Inspector. Create a server with one `greet` tool. By the end of this guide, an MCP client will call it with a name and receive a validated JSON response. ## Prerequisites This guide uses Node.js and npm. Use **Node.js 24.20.0 or later in the 24.x line**, with npm available in your terminal. Check your version with `node --version`. You will install TypeScript as a development dependency. Toolgrain supports TypeScript 5.5.4 or later with strict mode and Zod `^4.6.6`. ## Build and call your server **1. Create a project** Create a directory and install matching stable Toolgrain packages from npm's `latest` tag, along with Zod and the TypeScript tools: ```bash theme={null} mkdir hello-toolgrain cd hello-toolgrain npm init -y npm install @toolgrain/mcp @toolgrain/node zod@^4.6.6 npm install --save-dev typescript @types/node@^24.10.0 ``` `@toolgrain/mcp` provides the authoring API. `@toolgrain/node` provides the stdio transport used below. Zod describes and validates your tool's data. **2. Define your tool and server** Save this as `server.mts`. The `.mts` extension identifies the file as an ES module. ```ts server.mts theme={null} import { createServer, tool } from "@toolgrain/mcp"; import { stdio } from "@toolgrain/node"; import { z } from "zod"; const greet = tool({ title: "Greeting", description: "Greet someone by name", annotations: { readOnlyHint: true }, input: z.object({ name: z.string().min(1) }), output: z.object({ message: z.string() }), execute: ({ name }) => ({ message: `Hello, ${name}!` }), }); const server = createServer({ name: "hello-server", version: "1.0.0", tools: { greet }, }); await server.listen(stdio()); ``` The key `greet` in `tools: { greet }` is the name exposed to MCP clients. Toolgrain validates the input before calling `execute`, then validates its return value against the output schema. **3. Compile the server** Compile the file with strict checking and Node's ES module resolution: ```bash theme={null} npx tsc server.mts --strict --module NodeNext --target ES2022 --types node ``` This creates `server.mjs`, which Node can run. **4. Call your tool** Run this command from the same project directory: ```bash theme={null} npx --yes @modelcontextprotocol/inspector@2.11.0 --cli node server.mjs --protocol-era modern --format json --method tools/call --tool-name greet --tool-arg name=Ada ``` [MCP Inspector](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector) starts the server, calls `greet`, prints the response, and exits. The `--protocol-era modern` option selects MCP `2026-07-28`. Look for this value in `result.structuredContent`: ```json theme={null} { "message": "Hello, Ada!" } ``` The result also includes a text representation of the same JSON in `content`. Change `name=Ada` to try a different greeting. ## Connect an MCP client Configure your client to launch `node` with the **absolute path to `server.mjs`** as its argument. The client starts the stdio process and exchanges MCP messages through stdin and stdout. > [!TIP] > > Keep application logs on stderr, for example with `console.error()`. Stdout > carries MCP messages. A stdio server waiting quietly for requests is expected. See [client compatibility](/compatibility/protocol) for verified clients, versions, and setup instructions. ## Use HTTP Keep the tool and server definitions. Replace the `stdio` import and the final `server.listen()` call with: ```ts theme={null} import { http } from "@toolgrain/node"; await server.listen(http({ port: 3333 })); ``` Compile again and start the server: ```bash theme={null} npx tsc server.mts --strict --module NodeNext --target ES2022 --types node node server.mjs ``` Configure your MCP client's HTTP connection to use `http://127.0.0.1:3333/mcp`. The listener binds to loopback by default. Call `server.close()` from your application's shutdown path when integrating it into a larger application. For an existing HTTP listener, use a Web or Node handler. The [transport guide](/transports/overview) covers host configuration, HTTP headers, and framework integration. ## Next steps > [card] [Write more tools](/tools/overview) > > Add schemas, rich results, request context, and cooperative cancellation. > [card] [Try an example application](/examples) > > Explore stdio, HTTP frameworks, and protected endpoints. # Shared authorization API Source: https://toolgrain.mintlify.app/reference/auth Shared authorization providers, scopes, accessors, and errors. All exports on this page come from `@toolgrain/mcp`. JWT and Clerk implement this provider contract and supply their own identity types/accessors. ## AuthProvider ```ts theme={null} interface AuthProvider { readonly type: symbol; readonly resource?: string; readonly authorizationServers: readonly string[]; readonly scopesSupported?: readonly string[]; verify(accessToken: string, options: AuthVerifyOptions): Promise; } interface AuthVerifyOptions { readonly signal: AbortSignal; readonly resource: string; } ``` `type` identifies the provider/accessor pairing. Use a stable registered symbol when compatible package copies must interoperate. `verify()` must honor cancellation where possible and return structured-cloneable plain identity data. Toolgrain copies/freezes the verified identity per request. Custom providers own cryptographic verification and their application-specific checks. `AuthMetadata` contains optional `resource`, readonly `authorizationServers`, and optional readonly `scopesSupported`; `server.getAuthMetadata()` returns a fresh copy when configured. Supported scopes describe the resource's discovery catalog, not a required-scope policy. Omission leaves `scopes_supported` absent; `[]` advertises an empty catalog. Scope arrays are validated and copied at construction. `AuthReadonly` recursively describes the frozen identity view, including arrays. ## createAuthAccessor ```ts theme={null} createAuthAccessor(type: symbol) // returns (ctx: ToolContext) => AuthReadonly ``` The accessor is synchronous and rejects contexts without a matching verified identity. Register a provider with the same symbol. It does not verify a token on access. A direct `toolContext()` has no HTTP auth identity. ## AuthError and isAuthError ```ts theme={null} new AuthError(code: AuthErrorCode, options?: ErrorOptions & { description?: string; requiredScopes?: readonly string[]; }) isAuthError(value: unknown): value is AuthError ``` `AuthErrorCode` is `"invalid_request" | "invalid_token" | "access_denied" | "insufficient_scope" | "temporarily_unavailable"`. The error exposes `code`, optional public `description`, and optional readonly `requiredScopes`; `cause` stays private. Only put safe, intentional client guidance in `description`. `isAuthError()` recognizes compatible branded errors. Use `requiredScopes` only with `insufficient_scope`; other codes reject it with `TypeError`. The array is validated, copied, and frozen. When a verifier throws this error, HTTP adapters emit a 403 Bearer challenge with `error="insufficient_scope"` and, for a nonempty array, a space-delimited `scope`. Omitted or empty required scopes omit that challenge field. Supported resource scopes are never substituted for required scopes. Tool-handler exceptions retain the [tool error contract](/tools/errors). | Code | HTTP status | | - | - | | `invalid_request` | 400 | | `invalid_token` | 401 | | `access_denied` | 403 | | `insufficient_scope` | 403, with a Bearer challenge | | `temporarily_unavailable` | 503 | Unexpected auth failures, including provider outages, reach `onError` once without tool/request details; expected rejections and cancelled late failures do not. Do not convert every trusted-key or upstream failure into `invalid_token`. ## AuthScope `server.authorize(token, { resource, signal? })` returns a server-bound, single-use `AuthScope`. It exposes readonly `signal` and `dispose(): void`. Pass the scope to `server.handle(message, { auth: scope })` exactly once and always dispose it in `finally`. Scope verification/body reading/tool work observe cancellation and server close. ## Validation helpers `validateAuthScopes(scopes: readonly string[]): readonly string[]` validates unique RFC 6749 scope tokens and returns a frozen copy preserving case and order. Empty arrays are valid. Empty tokens, duplicates, whitespace, quotes, backslashes, non-ASCII characters, and non-array inputs throw `TypeError` without echoing values. Custom providers' `scopesSupported`, integration options, and `AuthError.requiredScopes` use the same validation. `validateAuthUrl(value: string): string` validates authorization/resource URLs, requiring HTTPS except permitted loopback HTTP. `validateTokenAudience(audience: unknown, resource: string): void` checks a verified token's audience, accepts a string or all-string array, and throws `AuthError("invalid_token")` for missing/mismatched audiences with safe public guidance. Call it **after** token verification; it does not authenticate arbitrary claims. For complete provider examples and HTTP integration, see [authorization](/guides/authorization#custom-providers-and-direct-invocation). # @toolgrain/clerk Source: https://toolgrain.mintlify.app/reference/clerk Public exports and behavior of @toolgrain/clerk. ## clerk ```ts theme={null} clerk(options: ClerkOptions): AuthProvider ``` `ClerkOptions` requires `publishableKey: string` and `secretKey: string`, with optional `resource: string` and `scopesSupported: readonly ClerkOAuthScope[]`. Issuer is derived from the publishable key; resource defaults to the validated public HTTP endpoint. Keys are server configuration, not tool inputs. `scopesSupported` declares this resource's public scope catalog. It is validated and copied at provider construction and appears as `scopes_supported` in protected-resource metadata. Omission leaves that field absent; `[]` advertises no scopes. It does not enforce required scopes or change Clerk's OAuth settings. See [resource scopes](/guides/authorization#resource-scopes). ## Scope names `CLERK_OAUTH_SCOPES` is a frozen tuple of Clerk's documented built-ins: `openid`, `profile`, `email`, `offline_access`, `public_metadata`, `private_metadata`, and `user:org:read`. The last requires Organizations to be enabled. `ClerkBuiltInOAuthScope` is the closed literal union of that tuple. `ClerkOAuthScope` provides built-in autocomplete and also accepts custom scope names, which Clerk supports per instance. It is not a compile-time allowlist; configuration still rejects invalid OAuth scope syntax at runtime. Create custom scopes in Clerk and assign them to the appropriate OAuth applications before advertising them. Instance metadata and application settings determine which scopes clients may actually request. See [Clerk's scope documentation](https://clerk.com/docs/guides/configure/auth-strategies/oauth/how-clerk-implements-oauth#scopes). ```ts theme={null} import type { ClerkOAuthScope } from "@toolgrain/clerk"; const scopesSupported = ["openid", "profile", "posts:read"] satisfies readonly ClerkOAuthScope[]; ``` Use only the scopes your resource needs. Exporting the built-in catalog does not make every scope required or request it by default. Generic JWT/custom providers use provider-defined scope names; there is no universal closed OAuth scope list. The provider accepts verified Clerk OAuth JWT or opaque access tokens for a user and client. JWT token types must identify an access token, and required user/client claims must be present. Revoked/expired opaque tokens are rejected. Sessions, API keys, and M2M tokens are unsupported. ## useAuth ```ts theme={null} useAuth(ctx: ToolContext): AuthReadonly interface ClerkAuth { readonly userId: string; readonly clientId: string; readonly scopes: readonly string[]; } ``` The accessor is synchronous and provider-specific. Identity is copied/frozen per request; raw credentials and Clerk SDK methods are not exposed. Application code still enforces action-specific permissions/scopes. Toolgrain does not configure Clerk OAuth applications or run client login flows. See [Clerk setup](/authentication/clerk) and the [full authorization guide](/guides/authorization). # Context API Source: https://toolgrain.mintlify.app/reference/context Request context, direct-call helpers, and lazy provider contracts. These exports live in `@toolgrain/mcp`. Context is request-scoped and non-generic; application services are inferred through provider accessors. Resource readers receive the same `ToolContext` contract as tool handlers. ## ToolContext and request types ```ts theme={null} interface ToolContext { readonly signal: AbortSignal; readonly request: ToolRequest; readonly reportProgress: (update: ToolProgress) => Promise; } interface ToolRequest { readonly id: RequestId; readonly protocolVersion: SupportedProtocolVersion; readonly client?: ToolClient; readonly meta: Readonly>; } ``` `RequestId` and `SupportedProtocolVersion` come from protocol. `ToolClient` has optional `info` and `capabilities`, recursively readonly modern/legacy unions. The request, metadata, and client snapshots are deeply frozen per request. Client reports are unverified. Protocol-version checks do not narrow the union automatically. ## reportProgress and ToolProgress ```ts theme={null} interface ToolProgress { readonly progress: number; readonly total?: number; readonly message?: string; } ``` Await `ctx.reportProgress(update)` to respect write ordering and backpressure. The method is bound to its invocation and can be passed directly to application helpers. It resolves without sending when the client omitted `_meta.progressToken`, the caller supplied no delivery channel, or the invocation has completed or been cancelled. Direct contexts from `toolContext()` have no delivery channel. For active delivery, `progress` and any `total` must be finite numbers. Floating point values are allowed; each `progress` value must be strictly greater than the previous one. The first value may be zero, and `total` can be omitted when unknown. `message` is optional public text. Invalid updates reject; uncaught validation failures use the usual private diagnostics and generic tool error. Delivery failure aborts the invocation with `AbortError` reason `Progress delivery failed` and reaches `onError(error)` without tool details. In-flight reports can reject on cancellation; new reports after cancellation resolve without sending. Await reports during the invocation, and choose a reasonable reporting frequency. The first update sends immediately; subsequent updates are spaced at least 100 ms apart per invocation. Awaiting a report includes this pacing delay and delivery backpressure. Accepted updates are delivered in order before the final response; cancellation clears pending delays and suppresses queued updates. The client supplies a string or integer progress token unique among its active requests. Toolgrain rejects duplicate active tokens on a shared message connection with `-32602`, before executing the tool. Integer and string tokens are distinct. Tokens become reusable on completion or cancellation, and tokens on independent HTTP response streams remain isolated. See [handler context](/guides/request-context#report-progress) and [HTTP behavior](/transports/overview). ## toolContext ```ts theme={null} toolContext(options?: ToolContextOptions): ToolContext ``` `ToolContextOptions` accepts `signal?`, `request?: Partial`, and `context?` registrations. Omitted or undefined fields default individually: fresh signal, ID 0, modern revision, no client, empty metadata, and no providers. Each call creates a new provider cache; reusing the returned context reuses that cache. This is the supported direct-call construction helper. Handwritten contexts are not a compatibility promise. A direct tool `execute()` or resource `read()` call remains raw and does not authorize or validate data. ## createContext ```ts theme={null} createContext({ name: string, resolve: (ctx: ToolContext) => Value, }): ContextProvider> ``` `name` must be nonempty and is a diagnostic label, not the provider identity. The definition is immutable and has an opaque identity. Register it explicitly in a server or direct context's `context` array. ### ContextProvider | Member | Contract | | - | - | | `name` | Readonly diagnostic label | | `use(ctx)` | Always `Promise`; resolves lazily and caches a promise/value/failure per context | | `provide(resolve)` | Returns an immutable typed binding for the same identity | `ContextProvider` is a type-only export describing the inferred accessor/binding contract. Construct providers with `createContext()`. Duplicate registrations for one identity fail construction; distinct definitions can share a name. Missing providers reject on access. Factories may await other accessors; all dependencies must be registered. Direct, indirect, and concurrent cycles reject with a diagnostic chain. Shared diamonds are supported. Authorization and input validation precede factory startup. Accessors check cancellation before access/startup and after resolution. Values are returned unchanged and can contain mutable clients or functions. There is no automatic resource disposal, transaction management, synchronous accessor, or background-work support. See [the full context guide](/guides/context). # @toolgrain/http Source: https://toolgrain.mintlify.app/reference/http Public exports and behavior of @toolgrain/http. Runtime-independent Web Request/Response integration. It owns shared HTTP routing, host/origin checks, body limits, authorization integration, and protocol response shaping. It does not open a listener. ## createHttpHandler ```ts theme={null} createHttpHandler(server: Server, options?: HttpOptions): HttpHandler interface HttpHandler { (request: Request): Promise; readonly matches: (pathname: string) => boolean; } ``` The combined handler owns the MCP path and, when configured, public auth metadata. Use `matches()` for framework routing. Mount at the root before body parsing; caller signals and disconnects propagate to execution. Supplied option arrays are copied. ## HttpOptions | Field | Default | Contract | | - | - | - | | `path?: string` | `/mcp` | Absolute endpoint path; no query, fragment, whitespace, or dot-segment normalization | | `allowedHosts?: readonly string[]` | Loopback hosts, any port for externally owned listeners | Exact authorities, optionally port-qualified; empty denies all | | `allowedOrigins?: readonly string[]` | Empty | Exact URL origins; an absent Origin is allowed | | `maxMessageBytes?: number` | 1 MiB | Positive safe integer | Allowed authorities normalize case and default ports. Wildcards, schemes, and paths are invalid. Both URL authority and any supplied Host header must be allowed. `allowedOrigins` is validation, not CORS response generation. Applications own TLS, proxy trust, and listener lifecycle. ## createProtectedResourceMetadataHandler ```ts theme={null} createProtectedResourceMetadataHandler( server: Server, options?: Pick, ): (request: Request) => Promise ``` Standalone metadata factory for explicit route registration. It serves configured protected-resource metadata for public GET/HEAD requests with host validation. The combined handler includes that behavior already; filesystem routers must separately expose the metadata path. HTTP supports independent requests with JSON results. A tool's first client-requested progress update opens a POST SSE response; progress messages precede the final response and EOF. Consume or cancel the response body so backpressure and request cleanup can complete. Authorization scopes stay active through delivery; cancellation aborts only that invocation. Calls that send no progress retain JSON and ordinary HTTP error statuses. There is no event-stream GET, session state, subscription support, or resumability. See [HTTP behavior](/transports/http), [framework recipes](/transports/frameworks), and [auth routing](/guides/authorization). # @toolgrain/jwt Source: https://toolgrain.mintlify.app/reference/jwt Public exports and behavior of @toolgrain/jwt. ## jwt ```ts theme={null} jwt(options: JwtOptions): AuthProvider ``` | `JwtOptions` field | Contract | | - | - | | `issuer: string` | Required trusted exact issuer URL | | `jwksUrl?: string` | Explicit signing-key endpoint; otherwise discover from issuer | | `resource?: string` | Explicit expected audience/resource; otherwise use validated HTTP resource | | `scopesSupported?: readonly string[]` | Validated, copied resource scope catalog for discovery; omission is unspecified, `[]` declares none; does not enforce required scopes | | `algorithms?: readonly string[]` | Defaults to RS256 and ES256; nonempty asymmetric allowlist | Supported asymmetric algorithms are RS256/384/512, PS256/384/512, ES256/384/512, EdDSA, and Ed25519. Availability still depends on the supported runtime/crypto implementation. Token signatures, issuer, required expiration, optional not-before, audience, and standard claim shapes are checked. Key discovery/rotation caches are internal, not a public key-management API. ## useAuth ```ts theme={null} useAuth(ctx: ToolContext): AuthReadonly interface JwtAuth { readonly claims: JwtClaims; } ``` `JwtClaims` has required `iss: string`, `aud: string | readonly string[]`, and `exp: number`. Optional standard fields are `sub`, `iat`, `nbf`, and `jti`. Other claims remain `unknown` through the index signature and require application validation. NumericDate fields are finite; audience arrays contain only strings. The synchronous accessor requires a matching verified JWT identity. It does not expose a token or refresh/login methods. Missing/mismatched audiences receive safe public resource guidance. Unexpected key/discovery failures are provider outages and remain private in diagnostics. See the [JWT guide](/authentication/jwt) and [shared auth contracts](/reference/auth). # @toolgrain/mcp Source: https://toolgrain.mintlify.app/reference/mcp Public exports and behavior of @toolgrain/mcp. The public authoring API for reusable tools and servers. Import protocol wire definitions directly from `@toolgrain/protocol`; MCP does not re-export them. See [installation](/getting-started/installation) for the published packages. ## createServer ```ts theme={null} createServer(options: ServerOptions): Server ``` | `ServerOptions` field | Contract | | - | - | | `name`, `version` | Required server identity strings | | `tools` | Required registration-name → `tool()` definition map | | `resources` | Optional readonly array of `resource()` definitions; an empty array enables an empty resource service | | `listPageSize` | Optional positive safe integer; maximum entries per tool/resource page, default `100` | | `instructions` | Optional server instructions | | `onError` | Optional `(error: unknown, details?: ToolErrorDetails) => void` diagnostic callback | | `auth` | Optional `AuthProvider`, for HTTP request authorization | | `context` | Optional readonly provider/binding array | Construction validates tool names, representable schemas, resource URIs/duplicates, metadata, and provider registrations. It does not open a transport. Registrations are snapshots; definitions remain reusable. ### List pagination `tools/list` and `resources/list` return at most `listPageSize` entries in registration order in both protocol revisions. For example: ```ts theme={null} const server = createServer({ name: "catalog", version: "1.0.0", tools, resources, listPageSize: 50, }); ``` Start without a `cursor`. When the result includes `nextCursor`, pass that exact string as `params.cursor` to the same list method. Continue until `nextCursor` is absent. Empty lists and final pages omit it; invalid cursors return JSON-RPC `-32602`. Cursors are opaque, reusable for the same server instance and list, and invalid after recreating the server. They require no HTTP session and do not grant authorization; every HTTP request authenticates normally. Each response contains copied metadata from the static registration snapshot. Listing does not run handlers, readers, or context providers. `getToolDefinitions()` still returns the complete copied tool list. `resources/templates/list` remains empty and rejects supplied cursors. For compatibility, `tools/list` also accepts an empty cursor as the first page; `resources/list` rejects it. ### Server methods | Method | Returns / behavior | | - | - | | `listen(transport)` | `Promise`; starts one `Transport` or `RequestTransport` | | `close()` | `Promise`; terminal, idempotent, re-entrant cleanup and cancellation | | `handle(message, options?)` | `Promise`; processes a complete decoded request | | `getToolDefinitions()` | Copied modern protocol tool metadata | | `getAuthMetadata()` | `AuthMetadata \| undefined` | | `authorize(token, { resource, signal? })` | `Promise`; server-bound, single-use authorization | `HandleOptions` contains optional `signal`, `protocolVersion`, `auth`, and `onNotification`. The protocol version is a supported revision; `auth` is a scope from this server. `onNotification(message: ProgressNotification)` may return `void` or `Promise` and delivers only progress for this request, with backpressure. Omit it for one-response callers; progress is then a no-op. Abort `signal` when the delivery channel closes. Always dispose an authorization scope in `finally`. `handle()` is not an HTTP validation boundary. A closed server cannot restart. Auth-configured servers reject message transports. ## tool ```ts theme={null} tool({ input, execute, output?, title?, description?, annotations?, icons?, _meta? }) ``` Returns a frozen branded `Tool`. `input` is a Zod 4 schema with an object root when exposed. `execute(input, ctx)` receives the schema's parsed output and required `ToolContext`. The optional output schema constrains return values and is parsed during server execution. `tool()` overloads infer schema/result types; users do not normally supply type arguments. `ToolDefinition` describes the authored fields and raw handler. `ToolMetadata` is the readonly protocol metadata subset. `ToolMap` is the heterogeneous registration contract. `Tool` is a type-only export describing the branded definition; construct definitions with `tool()`. Raw objects/spreads are not valid registrations. `definition.execute` remains a direct handler call, bypassing server processing. See [definitions](/tools/definitions), [validation](/tools/validation), and [request context](/guides/request-context). ## resource ```ts theme={null} resource({ uri, name, read, title?, description?, mimeType?, annotations?, size?, icons?, _meta? }) ``` Returns a frozen reusable resource whose URI belongs to the definition. Readers receive `(uri, ctx: ToolContext)` and return `{ contents, _meta? }` synchronously or asynchronously. Register definitions through `ServerOptions.resources`. See the [resource API reference](/reference/resources) and [resource guide](/guides/resources). ## mcpResult ```ts theme={null} mcpResult({ content, structuredContent?, isError?, _meta? }) ``` Wraps explicit MCP content. `content` is a required readonly array of protocol content blocks. `structuredContent` must be JSON-compatible. Result `_meta` carries metadata; `isError` explicitly marks safe public tool feedback. Conversion validates/copies content and supplies serialized structured text. | Exported type | Meaning | | - | - | | `McpResultOptions` | Authoring envelope: `content`, optional structured data, error flag, metadata | | `McpResult` | Branded explicit result wrapper, with readonly `value` | | `McpStructuredResult` | A result guaranteed to include structured content | | `McpErrorResult` | A result guaranteed to have `isError: true` | Overloads preserve structured-data presence and explicit error flags. Successful results with an output schema require structured content; text-only explicit errors remain valid. Use `McpStructuredResult` for typed reusable helpers, rather than widening to a possibly unstructured result. [Result rules](/tools/results) cover conversion differences between revisions. ## Content helpers These helpers are available in Toolgrain 0.3.0 or later. Typed constructors for blocks passed to `mcpResult({ content: [...] })`: | Method | Arguments / result | | - | - | | `content.text(text, options?)` | String and optional `ContentOptions`; text block | | `content.image(options)` | `ImageContentOptions` with required `data` and `mimeType`; image block | | `content.audio(options)` | `AudioContentOptions` with required `data` and `mimeType`; audio block | | `content.resourceLink(options)` | `ResourceLinkOptions` with required `uri` and `name`; resource-link block | | `content.resource(value, options?)` | `ResourceContentOptions` with required `uri` and either `text` or `blob`, plus optional `ContentOptions`; embedded-resource block | `BinaryContentData` is a base64 string or `Uint8Array`, including Node `Buffer`. Image/audio `data` and binary resource `blob` accept this type. Byte views are encoded synchronously; strings pass through unchanged. Image/audio MIME types are explicit. Resource MIME types are optional. `ContentOptions` contains optional `annotations` and `_meta`. Image, audio, and resource-link options include these fields directly. Embedded resources keep their own `_meta` inside `value`; the second argument describes the enclosing block. All options accept readonly inputs, and returned blocks have readonly types with literal `type` discriminators. The `content` namespace is frozen. Its methods construct ordinary blocks without I/O or registration. They do not mutate inputs, deeply freeze returned objects, or validate media bytes/base64 strings. Nested metadata remains referenced until server result conversion validates and copies the content. See [rich-content examples](/tools/results#content-types) for composition and client-presentation limits. ## Errors and diagnostics * `ToolNameError(toolName)` exposes `toolName` for an invalid registration key. * `ToolSchemaError(toolName, cause, schemaKind?)` exposes the underlying cause and `schemaKind`, defaulting to `"input"`; other kinds are `"output"` and `"metadata"`. * `ToolErrorDetails` contains readonly `toolName` and frozen `request: ToolRequest`. Arguments and auth identity are not added. Resource failures invoke `onError(error)` with the original error and no tool details; clients receive a generic JSON-RPC internal error. `onError` receives original unexpected failures. Expected protocol/input/explicit tool errors are not reported, late cancelled failures are suppressed, and diagnostics cannot interrupt cleanup or a response. See [error handling](/tools/errors). ## MCP Apps `getAppSupport(ctx): AppSupport` reads the current client claim and returns `"supported"`, `"not-advertised"`, or `"unknown"`. Claims are advisory, not authorization. See the [Apps reference](/mcp-apps/reference). ## Other exports The [context reference](/reference/context) covers `ToolContext`, `ToolProgress`, `ToolRequest`, `ToolClient`, `ToolContextOptions`, `toolContext`, `ContextProvider`, and `createContext`. The [auth reference](/reference/auth) covers shared authorization exports. [Custom transports](/transports/custom) use the following public contracts: ```ts theme={null} interface TransportCallbacks { onMessage(message: unknown): void; onParseError(error: unknown): void; onError(error: unknown): void; onClose(): void; } interface Transport { readonly mode?: "message"; start(callbacks: TransportCallbacks): Promise; send(message: ProtocolResponse | ProgressNotification): Promise; close(): Promise; } interface RequestTransport { readonly mode: "request"; start(server: Server, callbacks: Pick): Promise; close(): Promise; } ``` `ProtocolResponse` and `ProgressNotification` above are imported from protocol. Custom message transports must accept both responses and progress notifications. There is no exported internal registry, adapter, or separate core package. [Public source](https://github.com/keshavkatwe/toolgrain/blob/main/packages/mcp/src/index.ts). # @toolgrain/node Source: https://toolgrain.mintlify.app/reference/node Public exports and behavior of @toolgrain/node. Node-specific transports and IncomingMessage/ServerResponse adapters. The authoring API remains in `@toolgrain/mcp`. ## stdio ```ts theme={null} stdio(options?: StdioOptions): Transport ``` | `StdioOptions` field | Default / contract | | - | - | | `input` | `process.stdin`; Node `Readable` | | `output` | `process.stdout`; Node `Writable` | | `maxMessageBytes` | 1 MiB; positive safe integer, excluding newline | The transport is single-use and newline-delimited UTF-8 JSON. Parse errors permit subsequent frames; oversized frames terminate. Close detaches/pauses input without destroying caller-owned streams. See [stdio behavior](/transports/stdio). ## http ```ts theme={null} http(options?: HttpTransportOptions): HttpTransport ``` `HttpTransportOptions` extends `HttpOptions` with `port?: number` (default 3000; 0 requests an ephemeral port) and `hostname?: string` (default `127.0.0.1`). Ports must be integers from 0 through 65535. Bind addresses and allowed authorities are independent. `HttpTransport` extends `RequestTransport`, adds `address(): AddressInfo | undefined`, and owns the listener. The address is copied, available after successful startup, and absent before startup or after close. Managed default allowed hosts are loopback authorities on the actual port. Close stops the listener and active connections; instances cannot restart. ## createNodeHttpHandler ```ts theme={null} createNodeHttpHandler(server: Server, options?: HttpOptions) ``` Returns an asynchronous Node handler accepting `IncomingMessage`, `ServerResponse`, and optional middleware `next`. Mount it at the application root before body parsing. It combines MCP and configured auth metadata routes. Unmatched paths delegate untouched when `next` is supplied, otherwise return 404. The application owns the listener and must close it separately. ## createNodeProtectedResourceMetadataHandler ```ts theme={null} createNodeProtectedResourceMetadataHandler( server: Server, options?: Pick, ) ``` Returns a standalone Node protected-resource metadata handler, useful for routers that explicitly mount the well-known path. Host checks still apply. Applications must make the correct public path reachable. ## HttpOptions Re-exported from `@toolgrain/http`: `path?`, `allowedHosts?`, `allowedOrigins?`, and `maxMessageBytes?`. See [HTTP reference](/reference/http) for defaults and validation. Node ignores forwarded headers and preserves the direct scheme, request target, and Host authority. Trusted proxy normalization remains application-owned. # @toolgrain/protocol Source: https://toolgrain.mintlify.app/reference/protocol Public exports and behavior of @toolgrain/protocol. Wire types, protocol constants, and provenance. This package has no runtime dependencies and does not provide validators, dispatchers, transports, or a server implementation. ## Revision constants ```ts theme={null} import { PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, type SupportedProtocolVersion, type ProtocolResponse, } from "@toolgrain/protocol"; ``` `PROTOCOL_VERSION` is `"2026-07-28"`. `LEGACY_PROTOCOL_VERSION` is `"2025-06-18"`. `SUPPORTED_PROTOCOL_VERSIONS` is their readonly tuple, and `SupportedProtocolVersion` is its element union. The upstream root also exports its original `LATEST_PROTOCOL_VERSION` constant. `ProtocolResponse` is the shared response-envelope union used by transport contracts; `LegacyJSONRPCErrorResponse` models legacy errors, including null IDs that the older upstream schema cannot express. ## Wire definitions Modern upstream definitions are exported unchanged from the package root, including request/result/notification types, JSON-RPC envelopes, implementation/capability types, tool/content/resource/prompt shapes, and protocol error constants. Types describing methods do not mean Toolgrain's server implements those methods. Consult the [supported feature scope](/compatibility/overview). Legacy definitions are a separate entry point: ```ts theme={null} import type { Tool, CallToolResult } from "@toolgrain/protocol"; import type * as Legacy from "@toolgrain/protocol/2025-06-18"; ``` Use the revision-specific type rather than coercing one era's envelope into another. The complete wire contract is the unchanged [modern schema source](https://github.com/keshavkatwe/toolgrain/blob/main/packages/protocol/src/vendor/2026-07-28/schema.ts) and [legacy schema source](https://github.com/keshavkatwe/toolgrain/blob/main/packages/protocol/src/vendor/2025-06-18/schema.ts), which are the authoritative reference for all upstream exports. ## Provenance Both schemas are pinned to upstream commit `271ecc9accafdd9b83a3c869fa67c22953b2af80`. Revision folders retain their checksums, provenance, and upstream license. Corresponding JSON schemas are test-only conformance fixtures, not runtime exports or files copied to `dist`. MCP runtime validation remains in `@toolgrain/mcp`. Import wire types directly from protocol; MCP does not re-export them. See [licensing](/project/licensing) for mixed-content notices and update boundaries. ## MCP Apps extension The separate `@toolgrain/protocol/apps` export provides Apps revision constants and wire contracts. See [Apps reference](/mcp-apps/reference). It does not change the pinned core protocol schemas or supported outer revisions. # Resource API Source: https://toolgrain.mintlify.app/reference/resources Resource definitions, metadata, readers, and server registration. These authoring exports live in `@toolgrain/mcp`. Wire types such as `TextResourceContents`, `BlobResourceContents`, and protocol `Resource` come directly from `@toolgrain/protocol`. ## resource ```ts theme={null} resource>( definition: ResourceDefinition, ): Resource ``` Returns a frozen branded definition and preserves the reader's inferred return type. The reader must be a function. Metadata is validated and copied when the definition is registered with a server; construction does not read content. ### ResourceDefinition and ResourceMetadata `ResourceDefinition` combines readonly protocol resource metadata with `read(uri: string, ctx: ToolContext): Result`. | Field | Contract | | - | - | | `uri` | Required absolute URI; exact-match registry identity | | `name` | Required nonempty resource name | | `title`, `description`, `mimeType` | Optional display strings | | `annotations` | Optional audience, priority, and modification hints | | `size` | Optional nonnegative safe integer raw byte count | | `icons` | Optional readonly display icons; omitted in legacy listings | | `_meta` | Optional JSON-compatible metadata copied into listing entries | | `read` | Required synchronous or asynchronous reader, invoked only on reads | `ResourceMetadata` is the readonly protocol resource description. `Resource` is a type-only export describing the branded definition; construct it with `resource()`. Like tools, compatible duplicate package copies recognize each other's definitions. Object spreads must pass through the helper again before registration. ## ResourceReadResult ```ts theme={null} interface ResourceReadResult { readonly contents: readonly ( | (Readonly & { readonly blob?: never }) | (Readonly & { readonly text?: never }) )[]; readonly _meta?: Readonly; } ``` This sketch omits recursive readonly details. Nested authoring arrays and metadata also accept readonly inputs. Text/blob entries supply their own absolute URI and optional MIME type/metadata. Toolgrain does not fill these fields from listing metadata or automatically encode binary data. Return base64 strings for `blob`. Empty contents are valid for an existing resource. Results and metadata are validated and copied at server conversion; direct `read()` calls bypass this work. ## Server registration `ServerOptions.resources?: readonly Resource[]` registers the static resource list. The optional array enables the capability even when empty. Duplicate URIs, invalid metadata, or unbranded definitions fail construction. `tools` remains required; resource-only applications pass `tools: {}`. `ServerOptions.listPageSize` controls tool and resource list pages (default `100`). Follow `nextCursor` until absent; see [list pagination](/reference/mcp#list-pagination). The same reader and metadata serve both supported revisions and every authorized caller. Context uses existing auth accessors, lazy providers, and cooperative cancellation. See [resource behavior](/guides/resources#protocol-behavior-and-limits) for response fields, error codes, and deferred features. # Define and compose tools Source: https://toolgrain.mintlify.app/tools/definitions Define tools once, name them at registration, and create typed variants. `tool()` creates a frozen, reusable definition. It does not bind the tool to a transport or server. `createServer({ tools })` registers definitions and validates the exposed schema and metadata. ```ts theme={null} import { createServer, tool } from "@toolgrain/mcp"; import { z } from "zod"; const greet = tool({ title: "Greeting", description: "Return a greeting for a person", annotations: { readOnlyHint: true, openWorldHint: false }, input: z.object({ name: z.string() }), execute: ({ name }) => `Hello, ${name}!`, }); const server = createServer({ name: "hello", version: "1.0.0", tools: { "people.greet": greet }, }); ``` ## Names and metadata The registration key defines the exposed tool name; the variable name and title do not. Names must contain 1–128 ASCII letters, digits, underscores, hyphens, or dots. Invalid names throw `ToolNameError` at server construction. Optional fields are `title`, `description`, `annotations`, `icons`, and `_meta`. Annotations describe behavior to clients; they are hints, not an authorization boundary. Be accurate about whether a tool writes data, repeats safely, or interacts with an open world. Icons and nested protocol arrays may be readonly authoring inputs. Legacy listings omit icons. ## Reuse and variants Register the same definition on independent servers. To make a variant, pass a modified spread through `tool()` again: ```ts theme={null} const enthusiastic = tool({ ...greet, description: "Return an enthusiastic greeting", execute: ({ name }) => `Hello, ${name}! Great to see you.`, }); ``` Variants preserve schema inference and output presence. Changing a schema rechecks the handler against the changed type. Do not register `{ ...greet }` directly: raw objects and spreads lack the definition's brand and are rejected by types and at runtime. ## Direct calls are raw `definition.execute(input, ctx)` calls the application handler directly. It bypasses server authorization, input/output parsing, and MCP result conversion. Use `toolContext()` when constructing contexts for direct tests. To test the public tool contract, call through a server instead; see [testing](/guides/testing). Definitions are frozen, but application-owned services closed over by a handler remain your responsibility. Read the [validation guide](/tools/validation) for schema conversion and [result handling](/tools/results) for return values. # Errors and private diagnostics Source: https://toolgrain.mintlify.app/tools/errors Give clients useful feedback and keep unexpected failures in private diagnostics. Toolgrain distinguishes protocol errors, expected tool feedback, and unexpected application failures. This keeps useful validation feedback public without disclosing provider errors or internal exceptions. | Situation | Client sees | `onError` | | - | - | - | | Unknown tool or invalid protocol message | Protocol error | Not for expected rejections | | Ordinary invalid input | Tool error with validation feedback | Not reported | | Valid explicit `mcpResult({ isError: true })` | Your public content | Not reported | | Unexpected parsing, output, handler, or provider failure | `Tool execution failed`, no structured data | Original thrown value plus tool details | | Unexpected auth failure or provider outage | Auth response | Original value, no tool details | | Failure after cancellation | No late response | Suppressed | ## Configure diagnostics ```ts theme={null} const server = createServer({ name: "hello", version: "1.0.0", tools: { greet }, onError(error, details) { console.error("Toolgrain error", { error, tool: details?.toolName, requestId: details?.request.id, }); }, }); ``` `ToolErrorDetails` is frozen and contains `toolName` and the existing frozen `ToolRequest`. Tool arguments and auth identity/credentials are not added. Request metadata is client-supplied; assess what you log and do not assume arbitrary metadata is safe or verified. Transport and internal request diagnostics retain the one-argument form. Existing single-argument callbacks continue to work. Synchronous throws and asynchronous rejections from diagnostics cannot disrupt the response or cleanup. ## Construction failures `ToolNameError` identifies an invalid registration key. `ToolSchemaError` includes the tool name, `schemaKind` (`input`, `output`, or `metadata`), and the underlying cause. Correct these before starting the server; they are not tool-call errors. ## Public application errors Use an explicit error result only for feedback you intend the client to receive. Do not copy raw database, network, or provider exceptions into it. A direct call to a handler or provider accessor retains raw thrown values; private server error conversion applies when executing through the server. # Tool authoring Source: https://toolgrain.mintlify.app/tools/overview The complete tool authoring contract, from schemas to results and diagnostics. Define a tool once, then compose it into a server over stdio or HTTP. This guide covers schemas, handler context, results, and errors. ## Authoring API ```ts theme={null} import { createServer, tool } from "@toolgrain/mcp"; import { stdio } from "@toolgrain/node"; import { z } from "zod"; const greet = tool({ title: "Greeting", description: "Greet someone by name", annotations: { readOnlyHint: true, openWorldHint: false }, input: z.object({ name: z.string().min(1) }), output: z.object({ message: z.string() }), execute: ({ name }) => ({ message: `Hello, ${name}!` }), }); const server = createServer({ name: "hello-server", version: "1.0.0", tools: { greet }, }); await server.listen(stdio()); ``` Input and output schemas can use Zod 4 Classic or Zod Mini, including mixed definitions. Handler inputs still infer the parsed type, and declared outputs check the handler's return type before output parsing. For example, Mini users can define the same tool with its functional schema API: ```ts theme={null} import * as mini from "zod/v4/mini"; const greet = tool({ input: mini.object({ name: mini.string().check(mini.minLength(1)) }), output: mini.object({ message: mini.string() }), execute: ({ name }) => ({ message: `Hello, ${name}!` }), }); ``` Toolgrain consumes user schemas through `zod/v4/core`. Its internal wire and metadata validators continue using Classic. The MCP authoring API supports TypeScript 5.5.4 or later with `strict` enabled. Supported Zod versions follow the `^4.6.6` peer range. MCP packages JavaScript source maps, declaration maps, and their original TypeScript sources for debugging and editor navigation. Public imports still resolve to compiled files in `dist`. For mapped Node stack traces, start your application with `node --enable-source-maps app.js`. Registration keys supply exposed names: 1–128 ASCII letters, digits, underscores, hyphens, or dots. Names are case-sensitive. Definitions are reusable across servers, and registrations must be created with `tool()`; raw objects and modified object spreads are rejected. Pass modified definitions through `tool()` again to check their schema/handler types. Definitions and `mcpResult()` values from a duplicate installed copy of a compatible `@toolgrain/mcp` version are recognized. Variants retain the original input and output schema types: ```ts theme={null} const friendlyGreet = tool({ ...greet, title: "Friendly greeting" }); ``` `tool()` accepts `title`, `description`, `annotations`, `icons`, and `_meta` directly. Tool annotations are descriptive hints, not access controls. Metadata must be JSON-compatible and is validated and copied when the server is created. Readonly icon arrays, including nested `sizes`, are accepted. Handlers receive asynchronously parsed input, including defaults and transforms. An optional `output` schema constrains the handler return type and asynchronously parses successful returned data before serialization, applying output defaults, transforms, and refinements. Input JSON Schema describes the accepted input; output JSON Schema describes the parsed output. Unrepresentable schemas fail at server construction with `ToolSchemaError`. An output-side `.transform()` is not representable by itself; pipe it into a schema describing the parsed value, such as `z.string().transform(Number).pipe(z.number())`. Optional output properties that parse to `undefined` are omitted. Without `output`, handlers must return a string, JSON value, or `mcpResult()` whose structured content is JSON-compatible. Toolgrain checks the value at runtime but does not parse or transform it before result conversion; `undefined` inside that data is rejected rather than dropped. `execute` on a definition is the **raw handler**. Calling it directly bypasses input validation, output validation, and MCP result conversion. Invoke tools through the server's transport or `server.handle()` for the complete behavior. The registry is an internal module; there is no separate core package. ### Handler context Handlers receive a second argument, `ctx` (type `ToolContext`). Handlers that only take `input` remain valid. ```ts theme={null} const search = tool({ input: z.object({ query: z.string() }), async execute({ query }, ctx) { const response = await fetch( `https://example.com/search?q=${encodeURIComponent(query)}`, { signal: ctx.signal, }, ); return response.json(); }, }); ``` * `ctx.signal` is an `AbortSignal`. It aborts when a stdio client sends `notifications/cancelled`, when an HTTP caller's signal aborts (for example on disconnect), when the transport closes (including stdin EOF), or when the server closes. Its reason is an `AbortError`: "Request cancelled by client", "Connection closed" for stdio requests, or "Server closed" for `handle()` calls. When an HTTP caller's signal aborts, its own reason is used. A response is never sent after the signal aborts, so whatever the handler returns or throws afterwards is discarded. * `ctx.request` holds `id`, `protocolVersion`, an optional `client` with the `info` and `capabilities` the client reported, and `meta`, a copy of the request's `_meta`. Each request gets its own deeply frozen copies. Client info and capabilities are recursively readonly in the handler types, including nested arrays. Their types cover both supported protocol eras; fields that differ between eras need guards, and checking `protocolVersion` alone does not narrow them. Legacy details retain their reported values without normalization. Modern requests carry client details on each request; legacy stdio uses those from `initialize`; legacy HTTP has none, so `client` is absent. Client details are self-reported and unverified, so don't base security decisions on them. * If the request is cancelled while its input is still being validated, the handler is not started. * Cancellation is cooperative. A handler that ignores `ctx.signal` keeps running until it finishes; its response is still discarded, and on stdio its request ID stays in use until then. Calling `execute` directly requires a context. Build one with `toolContext()`, optionally passing a `signal` or `request` fields. `toolContext()` is the supported way to create a context: future versions may add required fields that it fills in, so contexts written out by hand can stop compiling. ```ts theme={null} import { toolContext } from "@toolgrain/mcp"; await search.execute({ query: "mcp" }, toolContext()); ``` ### Lazy context providers Use inferred accessors for application dependencies while keeping tools standalone: ```ts theme={null} import { createContext } from "@toolgrain/mcp"; const database = createContext({ name: "database", resolve: () => sharedDatabase, // Your application-owned client or pool. }); const useDatabase = database.use; const services = createContext({ name: "services", async resolve(ctx) { const db = await useDatabase(ctx); return { findUser: (id: string) => db.findUser(id, ctx.signal) }; }, }); const useServices = services.use; ``` Register `context: [services, database]` on `createServer()`, in any order. Handlers call `await useServices(ctx)`. Only accessed factories run; each tool call caches its provider promises and values. Use `database.provide(() => testDatabase)` for a typed server/test override, and `toolContext({ context: [...] })` for direct calls. Context values retain their original identity and applications own resource cleanup. See the [context guide](/guides/context) for a full example, cancellation, and errors. ### Rich results Return ordinary strings or JSON values for automatic conversion. Use `mcpResult()` for explicit MCP content, structured data, result metadata, or `isError`: ```ts theme={null} import { mcpResult, tool } from "@toolgrain/mcp"; import { z } from "zod"; const report = tool({ input: z.object({}), output: z.object({ uri: z.string() }), execute: () => mcpResult({ content: [{ type: "resource_link", uri: "https://example.com/report", name: "Report", }], structuredContent: { uri: "https://example.com/report" }, }), }); ``` The helper supports text, image, audio, resource links, and embedded text/blob resources. Content accepts readonly arrays and nested protocol fields, including `as const` values. Content and data are validated and copied during conversion. Optional result and content fields set to `undefined` are treated as absent. A JSON text block accompanies structured data unless an identical text block is already present. When an output schema changes the data, a text block containing the original JSON is updated to the parsed JSON instead of being duplicated. Ordinary objects containing `content` or `isError` remain application data; Toolgrain does not guess that they are protocol results. When `output` is declared, an explicit successful result must supply `structuredContent`; TypeScript checks its presence as well as its type. Use `McpStructuredResult` when explicitly annotating a helper that returns such a result. Any supplied structured data is parsed against the schema, including data in error results (`isError: true`). Errors may omit structured data and report text in `content`; output defaults do not create structured data for these errors. Without an output schema, structured data may be any valid JSON. Invalid outputs become tool errors without structured data. Modern results can contain any JSON value as structured content. Legacy structured content and advertised output schemas are limited to objects. Other values remain available as JSON text in legacy results. Legacy listings retain titles, annotations, and `_meta`, and omit icons. ### Errors and diagnostics Return `mcpResult({ isError: true, content: [...] })` for an error intended for the client. Valid explicit errors preserve their content, structured data, and metadata under the existing output-validation rules. Input validation failures also return public feedback identifying the rejected fields. Unexpected exceptions from input parsing, handlers, or context providers, along with invalid outputs, return `isError: true` with the generic text `Tool execution failed`, without structured data. Exception messages, stacks, and causes remain private. These failures reach the server's optional `onError(error, details)` callback once, with the original thrown value: ```ts theme={null} const server = createServer({ name: "projects", version: "1.0.0", tools: { listProjects }, onError(error, details) { console.error("Unexpected server failure", error, details); }, }); ``` For unexpected tool failures, `details` is a frozen `ToolErrorDetails` containing the exposed `toolName` and the context's frozen `request`: ID, protocol revision, optional client information, and request metadata. Toolgrain adds no arguments, verified identity, or bearer token to these details. Request metadata and client information retain the client-supplied values; keep diagnostics private. Unexpected auth verification failures, including provider `AuthError("temporarily_unavailable")` outages, also reach `onError` once with the original thrown value and no `details`. Expected auth rejections (`invalid_request`, `invalid_token`, and `access_denied`) do not. Auth responses keep their existing public error codes and optional provider-supplied descriptions. Transport and other internal request failures omit `details`. Existing callbacks taking only `error` remain supported. Callback throws and asynchronous rejections cannot replace the response or interrupt cleanup; diagnostics are not awaited. Explicit tool errors, ordinary input validation failures, and protocol errors do not reach `onError`. Failures after cancellation remain discarded without diagnostics. Direct definition `execute()` and provider accessor calls keep their raw return and rejection behavior; this boundary applies to server execution. # Return values and rich content Source: https://toolgrain.mintlify.app/tools/results Return JSON, rich MCP content, and intentional public errors. Return ordinary strings and JSON data for most tools. Use `mcpResult()` when you intentionally want MCP content blocks, explicit tool errors, or result metadata. | Handler return | Result without an output schema | | - | - | | String | Text content | | JSON object | Structured content plus serialized text | | JSON array, number, boolean, or null | Modern structured content plus text; legacy text only | | `mcpResult(...)` | Explicit content and metadata after validation | An ordinary object shaped like `{ content, isError }` is still application data. It is not interpreted as an MCP result without the helper. ## Structured data with narrative The `content` helpers below are available in Toolgrain 0.3.0 or later. You can also supply raw protocol content blocks to `mcpResult()`. ```ts theme={null} import { content, mcpResult, tool } from "@toolgrain/mcp"; import { z } from "zod"; const report = tool({ input: z.object({}), output: z.object({ count: z.number(), summary: z.string() }), execute: () => mcpResult({ content: [content.text("Report complete")], structuredContent: { count: 2, summary: "Two records matched." }, }), }); ``` Toolgrain supplies a text serialization for structured content. If output parsing changes the data, text generated from the original structured data is replaced with the parsed serialization. User-authored narrative blocks remain separate. The tested Claude Code client hides supplemental text when structured content is present. Put essential narrative in the structured data, or return text-only without an output schema when that is the intended contract. See [verified client behavior](/compatibility/clients). ## Content types `mcpResult()` supports text, image, audio, resource links, embedded text/blob resources, structured JSON, `isError`, and `_meta`. Image and audio blocks carry base64 data and a MIME type. Resource links and embedded resources are result content; they do not register a resource reader. Use [`resource()`](/guides/resources) and `ServerOptions.resources` to expose separately readable content. Use the [`content` helpers](/reference/mcp#content-helpers) to construct typed blocks. Extracted arrays retain their content discriminators without `as const`. Existing raw content blocks remain supported, and you can mix them with helper-created blocks. | Helper | Content | | - | - | | `content.text(text, options?)` | Text with optional annotations and `_meta` | | `content.image({ data, mimeType, ... })` | Inline image | | `content.audio({ data, mimeType, ... })` | Inline audio | | `content.resourceLink({ uri, name, ... })` | Link to a file or other resource | | `content.resource({ uri, text, ... }, options?)` | Embedded text file | | `content.resource({ uri, blob, ... }, options?)` | Embedded binary file | ```ts theme={null} import { content, mcpResult } from "@toolgrain/mcp"; // Your application supplies the file contents and the report URL. function reportResult(pngBytes: Uint8Array, wavBytes: Uint8Array, reportUrl: string) { const blocks = [ content.text("The report is ready."), content.image({ data: pngBytes, mimeType: "image/png" }), content.audio({ data: wavBytes, mimeType: "audio/wav" }), content.resourceLink({ uri: reportUrl, name: "report.pdf", mimeType: "application/pdf", }), content.resource({ uri: "report:///summary.txt", text: "Two records matched.", mimeType: "text/plain", }), content.resource({ uri: "report:///data.csv", blob: new TextEncoder().encode("id,total\n1,42\n"), mimeType: "text/csv", }), ]; return mcpResult({ content: blocks, structuredContent: { count: 2, summary: "Two records matched." }, _meta: { "example.com/report-id": "r_123" }, }); } ``` Image/audio `data` and resource `blob` accept a base64 string or `Uint8Array`, including Node `Buffer`. Helpers encode bytes synchronously and pass base64 strings through unchanged. They encode only the supplied byte view, without mutating it. Supply an explicit MIME type for images and audio. Helpers perform no file reads, URI fetching, MIME detection, or resource registration. Your application owns those operations. Resource links describe a resource; clients decide whether to fetch or display it. All helpers accept readonly authoring inputs and return blocks with readonly types. Nested annotations and metadata remain references to the supplied values until server conversion. For `content.resource(value, options)`, `value._meta` belongs to the embedded resource, while `options._meta` and `options.annotations` belong to the enclosing content block. Text and blob contents are mutually exclusive in the helper's type contract. Wrap helper blocks in `mcpResult()` to return rich content. The helpers construct ordinary objects, so returning one directly retains ordinary application-data semantics. They do not change output-schema validation or client presentation. Content is validated and copied at conversion. Undefined optional envelope fields are omitted; undefined inside unparsed structured data is rejected. Legacy structured content must be object-rooted. ## Expected errors ```ts theme={null} return mcpResult({ isError: true, content: [{ type: "text", text: "No matching record was found." }], }); ``` This message is intentionally public. Unexpected exceptions are kept private. Use [`McpStructuredResult`](/reference/mcp#mcpresult) when an explicitly typed helper must promise successful structured output. # Inputs, outputs, and inferred types Source: https://toolgrain.mintlify.app/tools/validation Understand asynchronous input and output parsing with Zod 4. Toolgrain accepts Zod 4 Classic and Mini user schemas. Handlers receive the **parsed output** of an input schema, including defaults and transforms. Validation uses asynchronous parsing, so asynchronous refinements are supported. ```ts theme={null} import { tool } from "@toolgrain/mcp"; import { z } from "zod"; const greet = tool({ input: z.object({ name: z.string().trim().min(1).default("friend") }), output: z.object({ message: z.string() }), execute: ({ name }) => ({ message: `Hello, ${name}!` }), }); ``` Omitting `name` produces `friend`; whitespace is trimmed before the handler runs. A declared output constrains the handler's return type and asynchronously parses the result too. ## Published schemas At server construction, Toolgrain converts input schemas using Zod's input mode and JSON Schema 2020-12. The root must be an object. Output schemas use output mode. A schema that can parse values is not necessarily representable in JSON Schema: unrepresentable schemas or invalid metadata throw `ToolSchemaError` during construction. Keep transformations inside a representable schema and check the converted result when using advanced Zod features. Input shape describes what clients should send; output shape describes the parsed value clients receive. Legacy clients see output schemas only when the root is an object. ## Output rules For ordinary results, the declared output parses the returned value directly. Defaults and transforms can change the structured data sent to a client. For explicit `mcpResult()` returns, any supplied `structuredContent` is parsed, including error data. Successful rich results with an output schema must include structured content in their public types and at runtime. An explicit `isError: true` result may omit structured content and return text alone. Output defaults do not invent data for such an error. Invalid output becomes a generic tool error without structured data, and the original failure reaches private diagnostics. Without an output schema, handlers' values are unchanged before MCP conversion. JSON data must be finite and serializable: reject undefined within unparsed data, bigint, functions, cyclic references, and class instances that are not supported JSON values. Strings become text; other valid JSON values become structured content where the protocol permits it. ## Cancellation during validation Once registry execution starts, validation may continue even if the request is cancelled. If the signal is aborted when input parsing finishes, the handler is not started. Late output and responses are suppressed. Cooperative cancellation cannot forcibly terminate asynchronous application work. # Custom transports and direct handling Source: https://toolgrain.mintlify.app/transports/custom Implement a transport or process complete protocol messages directly. Most applications should use the supplied adapters. Custom integrations can implement a message `Transport` or independent `RequestTransport`, or call `server.handle()` directly. Protocol methods do not belong in the framing adapter. ## Message transport `Transport` has `start(callbacks)`, `send(message)`, and `close()` methods; optional `mode` is `"message"`. `send()` accepts `ProtocolResponse | ProgressNotification`, imported from protocol. Preserve notification/response write order and resolve only after write/backpressure handling. On startup, retain callbacks for messages, parse failures, unexpected errors, and connection closure. Callbacks are synchronous; message processing runs independently. Own UTF-8 framing, JSON decoding, write ordering/backpressure, and stream cleanup. Do not call the MCP dispatcher yourself. Message transports are unsuitable for servers with HTTP authorization configured. ## Request transport `RequestTransport` declares `mode: "request"`. Its `start(server, callbacks)` receives the composed server plus `onError` and `onClose`; `close()` stops its listener. Each incoming request has its own validation, authorization scope, and cancellation signal. Never reuse a scope across requests. The server claims one transport before startup, across compatible package copies. Reusing a transport or attaching a second one is rejected; the existing owner remains running. Closure is terminal, idempotent, and re-entrant. ## Handle a complete protocol message ```ts theme={null} const controller = new AbortController(); const response = await server.handle({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "greet", arguments: { name: "Ada" }, _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}, }, }, }, { signal: controller.signal }); ``` `handle()` returns a protocol response or `undefined` for notifications/cancelled work. It does not perform HTTP method, host, Origin, content-type, or body-size checks. Implement those boundaries before direct handling, or reuse an HTTP adapter. To deliver client-requested progress, pass an optional `onNotification(message)` callback in the handle options. It receives `ProgressNotification` wire envelopes for that invocation and may return a promise to apply backpressure. Omit it for one-response integrations. Abort the request signal when the delivery channel closes, and await the final `handle()` response after the preceding notifications. For protected calls, obtain a server-bound scope with `authorize()`, pass it as `{ auth }`, and dispose it in `finally`. Scopes are single-use. The [detailed authorization guide](/guides/authorization#custom-providers-and-direct-invocation) shows that lifecycle. # Framework recipes Source: https://toolgrain.mintlify.app/transports/frameworks Mount Toolgrain in Express, Hono, Elysia, and Next.js. These recipes show the adapter boundary. Each assumes a Toolgrain `server` with registered tools; see the complete [examples](/examples) for runnable applications and lifecycle handling. Mount combined handlers at the application root so auth metadata is reachable. ## Express ```ts theme={null} import express from "express"; import { createNodeHttpHandler } from "@toolgrain/node"; const app = express(); app.use(createNodeHttpHandler(server)); app.use(express.json()); // Other application routes may parse JSON afterward. const listener = app.listen(3001, "127.0.0.1"); ``` Matched MCP responses keep their protocol/auth status; unrelated paths call Express's `next` before reading the body. Close both the application listener and Toolgrain server on shutdown. ## Hono ```ts theme={null} import { Hono } from "hono"; import { createHttpHandler } from "@toolgrain/http"; import { serve } from "@hono/node-server"; const app = new Hono(); const handler = createHttpHandler(server); app.use("*", (c, next) => handler.matches(c.req.path) ? handler(c.req.raw) : next(), ); const listener = serve({ fetch: app.fetch, hostname: "127.0.0.1", port: 3002 }); ``` The application owns Node listener shutdown and `server.close()`. ## Elysia ```ts theme={null} import { Elysia } from "elysia"; import { createHttpHandler } from "@toolgrain/http"; const handler = createHttpHandler(server); new Elysia() .onStop(() => server.close()) .mount(handler) .listen({ hostname: "127.0.0.1", port: 3003 }); ``` Run supported Bun applications on 1.4.4 or later within 1.x. The repository also has a protected Clerk Elysia example, kept separate from its ordinary credential-free flow. ## Next.js App Router For an unprotected endpoint, define the server once in a route module and export its Web handler: ```ts app/mcp/route.ts theme={null} import { createHttpHandler } from "@toolgrain/http"; import { server } from "../../lib/server.js"; const handler = createHttpHandler(server); export const POST = handler; export const GET = handler; export const DELETE = handler; export const runtime = "nodejs"; ``` Here `lib/server.ts` is your module exporting a composed server. Use explicit metadata factories in a matching well-known route when protecting a filesystem-routed endpoint; exporting `/mcp` alone does not make the public metadata path routable. Apply the same production host settings to both handlers. See [authorization integration](/guides/authorization#combined-handlers-for-existing-applications). The examples independently test plain Node, Express, Hono, Elysia, and Next.js. Fastify and NestJS are not separately verified; do not infer a tested integration from shared Request/Response types. # Streamable HTTP Source: https://toolgrain.mintlify.app/transports/http Choose a listener or handler and configure HTTP request validation. Toolgrain supports independent HTTP POST requests with JSON responses or request-scoped SSE progress. Choose a managed Node listener, Node middleware, or a Web handler depending on who owns your application listener. A tool's first client-requested `ctx.reportProgress()` update opens SSE; calls that send no updates retain JSON responses. Consume or cancel response bodies so streaming backpressure and cleanup can complete. | Application | Adapter | | - | - | | Standalone Node service | `http()` from `@toolgrain/node` | | Node HTTP or Express listener | `createNodeHttpHandler()` from `@toolgrain/node` | | Web Request/Response framework | `createHttpHandler()` from `@toolgrain/http` | ## Web handler ```ts theme={null} import { createHttpHandler } from "@toolgrain/http"; const handler = createHttpHandler(server, { path: "/mcp", allowedHosts: ["api.example.com"], maxMessageBytes: 1024 * 1024, }); const response = await handler(request); ``` `request` is the framework's Web `Request`. Use `handler.matches(pathname)` to determine whether the combined handler owns an MCP or metadata path before routing other traffic. ## Options and ordering `path` defaults to `/mcp`. `allowedHosts` contains exact authorities, optionally with ports; defaults allow loopback hosts. An empty list rejects all hosts. Schemes, paths, and wildcards are not valid entries. Both the public request URL and supplied Host authority must pass validation. An absent Origin is allowed. A present Origin must match `allowedOrigins`, which defaults to an empty list. This validation is distinct from CORS: applications implement any preflight handling and response headers they require. Host validation runs before routing, authorization, and body parsing for owned routes. Authorization runs before body parsing and tool work. Mount combined handlers at the application root before JSON middleware. Node middleware delegates unrelated paths to a supplied `next` callback without consuming the body. Without that callback, unmatched paths return 404. ## Protocol behavior Both supported revisions use the same tool definitions. Modern request metadata and required parameter headers must agree. Unsupported revisions, malformed requests, and invalid headers are rejected. Valid notifications produce no protocol response and are acknowledged as appropriate; they do not create session state. There are no sessions, event streams, resumability, or subscriptions in the current HTTP implementation. GET on the MCP endpoint does not open an event stream. When auth is configured, combined handlers separately route public GET/HEAD protected-resource metadata. For filesystem routers, explicit metadata handler factories are available. HTTP disconnects abort request signals. TLS, reverse-proxy trust, listener limits, CORS, and deployment remain application-owned. See [production guidance](/guides/production). # Transports Source: https://toolgrain.mintlify.app/transports/overview Detailed stdio and HTTP behavior, lifecycle, and adapter boundaries. Choose stdio for a process started by an MCP client, or HTTP for a network endpoint. Both use the same tool definitions. ## Node stdio and complete flow `@toolgrain/node` exports `stdio()`, using the process's stdin/stdout by default. It frames newline-delimited UTF-8 JSON, handles partial chunks, reports malformed messages, and serializes writes with backpressure. Diagnostics belong on stderr. `stdio({ input, output, maxMessageBytes })` accepts custom Node streams and an incoming-message byte limit (default 1 MiB, excluding the newline). Oversized messages terminate the transport. EOF or stream failure closes the attachment. Explicit close removes listeners and pauses input; it does not destroy or end caller-owned streams, or force the process to exit. Build and launch the example: ```sh theme={null} bun run build node apps/stdio-example/dist/index.js ``` To launch the MCP Inspector browser UI (run `bun run dev` or `bun run build` first): ```sh theme={null} bun run --cwd apps/stdio-example inspect ``` The script runs the official `@modelcontextprotocol/inspector` through `npm exec` outside the Bun-managed workspace and pins Inspector 2.11.0 and runs the compiled server with Bun and `--protocol-era modern` (Inspector defaults to legacy otherwise). In Inspector, connect to the server, list tools, and call `greet` with a name. See the [Inspector documentation](https://modelcontextprotocol.io/docs/2026-07-28/tools/inspector). Paste this single-line request into its stdin to call `greet`: ```json theme={null} {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"greet","arguments":{"name":"Ada"}}} ``` The response includes `structuredContent: {"message":"Hello, Ada!"}` and a text representation. Send `server/discover` or `tools/list` with the same `_meta` to inspect the server. Closing stdin ends the example naturally. `bun run test` includes subprocess integration tests that launch the compiled example and check discovery, tool listing/execution, malformed-input recovery, error responses, and EOF shutdown in both eras. These use a small test client; Inspector 2.11.0 and the installed Codex client are also verified over stdio and HTTP. Codex's normal initialization-based connection requires no modern flags; see the [compatibility report](/compatibility/protocol) for exact tested versions. ## Streamable HTTP `@toolgrain/http` provides `createHttpHandler(server, options?)`, a Web `Request` → `Promise` handler. `@toolgrain/node` provides `createNodeHttpHandler(server, options?)` for Node `IncomingMessage` and `ServerResponse`. Both share the same HTTP implementation; neither depends on a web framework. For a standalone Node listener, use: ```ts theme={null} import { http } from "@toolgrain/node"; await server.listen(http({ port: 3000, path: "/mcp" })); // await server.close(); // Stops the owned listener and active requests. ``` For an existing application, mount a combined handler at its root. It routes the configured MCP endpoint (default `/mcp`) and automatically serves public protected resource metadata when auth is configured. `allowedHosts` defaults to loopback hosts; configure exact public authorities for deployment. The framework owns its listener and calls `server.close()` during shutdown. ```ts theme={null} import { createHttpHandler } from "@toolgrain/http"; const handler = createHttpHandler(server, { path: "/mcp", allowedHosts: ["api.example.com"], allowedOrigins: ["https://example.com"], maxMessageBytes: 1024 * 1024, }); // Next.js App Router: app/mcp/route.ts export const POST = handler; export const GET = handler; export const DELETE = handler; ``` ```ts theme={null} import { createNodeHttpHandler } from "@toolgrain/node"; // Express: mount before express.json() or other body-consuming middleware. app.use(createNodeHttpHandler(server)); app.use(express.json()); app.get("/health", (_request, response) => response.json({ status: "ok" })); ``` The Node middleware calls `next()` for unrelated paths before consuming their bodies. Matched MCP errors remain Toolgrain responses. Web middleware can use `handler.matches(pathname)` to select the MCP and metadata routes and delegate other paths to its framework. The public factories compose focused internal modules. HTTP separates option normalization, endpoint checks, bounded body decoding, request/header validation, parameter-header schema extraction, execution, and response serialization. The Node adapter separates request conversion, connection abort tracking, and response writing with backpressure. HTTP protocol behavior stays in `@toolgrain/http`; Node modules only adapt the runtime interfaces. No generic utility package is needed for these responsibilities. Within HTTP, `modern/` and `legacy/` contain each era's version/header validation, notification rules, and response policies. `protocol-version.ts` selects one adapter per POST; body decoding, routing/parameter-header comparison, execution, and response serialization are shared. HTTP supports revisions `2026-07-28` and `2025-06-18`: independent POST requests and JSON responses or request-scoped SSE progress. Legacy initialization is supported without issuing session IDs or keeping global client negotiation state. There is no GET event stream or resumption. Subscriptions remain separate work. See [authorization](/guides/authorization) for JWT/Clerk and request identities. Requests must advertise both `application/json` and `text/event-stream` in Accept. When a client includes a string or integer `params._meta.progressToken`, tools can call `await ctx.reportProgress({ progress, total, message })`. The first update opens an SSE response with `Content-Type: text/event-stream`, `Cache-Control: no-store`, and `X-Accel-Buffering: no`. It carries `event: message` frames with JSON-RPC progress notifications, followed by the revision-specific final response and EOF. Calls that send no progress retain JSON responses and normal HTTP status handling. After SSE starts, later tool errors arrive in its final JSON-RPC response. Await progress reports to respect backpressure. A consumer must read the response body or cancel it; cancellation/disconnection aborts that invocation and suppresses late events. Authorization stays active through execution and final delivery, then is disposed. Closing the server also interrupts a final SSE write blocked by backpressure. Progress uses the originating POST response and does not open a subscription or GET event stream. No SSE resumption or event IDs are implemented. Every modern POST carries `MCP-Protocol-Version`, `Mcp-Method`, and, for tool calls, `Mcp-Name`. Header values must match the JSON-RPC body. Encoded names and declared `x-mcp-header` parameter annotations are validated before tool execution; invalid annotations fail HTTP-handler construction. Missing or mismatched headers return HTTP 400 / `HeaderMismatch`; unsupported versions return HTTP 400 with supported versions; unsupported RPC methods return HTTP 404. GET and DELETE return 405. Legacy `initialize` can omit the version header and declares its requested version in `params.protocolVersion`. Subsequent legacy POSTs carry `MCP-Protocol-Version: 2025-06-18`; modern routing headers are optional but checked against the body when present. Contradictory header/body versions are rejected. Legacy JSON-RPC method/argument errors use HTTP 200, while malformed transport messages still fail with HTTP errors. Legacy `notifications/initialized` and valid `notifications/cancelled` return HTTP 202 with no body. Cancellation is advisory: without a session or client identity, an independent notification cannot safely target another HTTP request, so it does not cancel shared work. Modern HTTP notifications remain unsupported. `maxMessageBytes` defaults to 1 MiB and limits incoming bytes, not output size. Bodies use strict UTF-8 decoding. Invalid JSON returns 400; oversized bodies return 413\. Already consumed bodies are rejected. Each HTTP request has its own execution scope, so concurrent callers can use the same JSON-RPC ID safely. Disconnects suppress the corresponding result; running validation and handlers continue under the existing tool execution semantics. An absent Origin is allowed. A present Origin must exactly match an entry in `allowedOrigins`, which defaults to an empty list. This is independent of CORS and authentication: applications own browser preflight handling, TLS, deployment configuration, and framework HTTP-server shutdown. Toolgrain owns MCP routing, host validation, and optional JWT/Clerk verification. Set explicit origins when using a browser client. The plain Node example binds to `127.0.0.1`. The MCP server exposes `handle(message, { signal?, protocolVersion?, onNotification? })` for independent decoded messages and `getToolDefinitions()` for fresh copies of advertised metadata. `onNotification` delivers request-scoped progress with asynchronous backpressure; omitting it makes reports a no-op. Direct callers own notification framing and must abort their signal when delivery closes. The HTTP adapter passes the validated revision per request; direct legacy callers supply `protocolVersion: LEGACY_PROTOCOL_VERSION` after initialization. Request processing shares dispatch/error conversion with stdio. `close()` is terminal and suppresses pending results across both paths; attached-transport EOF also closes the server. A listener attached through `http()` closes with the MCP server; externally mounted handlers leave the listener application-owned. Run the plain Node example after building: ```sh theme={null} bun run build bun run --cwd apps/http-example start ``` The endpoint is `http://127.0.0.1:3000/mcp`. See [independent framework examples](/examples) for verified Express, Hono, Elysia, and Next.js integrations. Framework dependencies live only in their respective example workspaces. NestJS is not separately verified. # Stdio transport Source: https://toolgrain.mintlify.app/transports/stdio Serve local clients through newline-delimited JSON on stdin and stdout. Use `stdio()` from `@toolgrain/node` when a client launches your server as a local process. The adapter handles framing and lifecycle; MCP method handling stays in `@toolgrain/mcp`. ```ts theme={null} import { stdio } from "@toolgrain/node"; await server.listen(stdio({ maxMessageBytes: 1024 * 1024 })); ``` ## Framing and limits Messages are newline-delimited UTF-8 JSON. The default incoming-message limit is 1 MiB, excluding the newline. Malformed JSON or UTF-8 reports a parse error and permits later messages. Oversized frames terminate the transport. Outgoing writes respect writable backpressure and preserve ordering. `input` and `output` may be supplied as Node streams; they default to `process.stdin` and `process.stdout`. A transport instance is single-use. A server accepts one transport, and close is terminal. ## Shutdown EOF is the normal stdio shutdown signal. Closing detaches listeners and pauses input without destroying or ending supplied streams or calling `process.exit()`. Active request signals abort on connection close. A handler that ignores its signal may continue running, but its response is discarded. Auth-configured servers reject message transports before startup. Use HTTP when configuring endpoint authorization. ## Operational guidance Keep all logs off stdout. Use absolute compiled entry-point paths in client configuration. Reconnect after rebuilding so the client launches a fresh process. Separate build output from protocol stdout. See [client setup](/getting-started/clients) and the [Node API](/reference/node).