Function: createToolGate()
createToolGate(
__namedParameters?):ToolGate
Defined in: toolGate.ts:202
Factory for a gate: a function that wraps a Tool so every call
passes the same authentication and authorization pipeline before its
handler runs. The gated tool is an ordinary Tool, so it registers
directly or joins a catalog like any other.
Every gated call:
- Resolves the caller identity (default:
getIdentity()). Returns anisErrorresult when the identity is absent (unauthenticated request). - When
enforceScopeistrue(default), checksrequiredScope— returns anisErrorresult when the scope is absent, consistent with how MCP surfaces authorization errors. - Runs global
gatesthen the tool'sgatesin order; a throwing gate rejects the call. Every gate receives the full ToolCallContext. - Merges
buildContextoutput into the handler args. - Calls
onErroron handler throw before rethrowing. - With
i18n, renders aLocalizedErrorfrom a gate or the handler as anisErrorresult in the caller's locale instead of rethrowing it.
Parameters
| Parameter | Type |
|---|---|
__namedParameters | CreateToolGateOptions |
Returns
Example
const gate = createToolGate({
resolveIdentity: () => {
const jwt = getIdentity<{ sub: string; scopes: string[] }>();
return { userId: jwt!.sub, scopes: jwt!.scopes };
},
});
registerTools({
server,
tools: [
gate({
requiredScope: 'campaigns:write',
// arg-conditional gate: active vs. inactive have different restrictions
gates: [
({ args }) =>
args.isActive
? subscriptionGate(['mustNotExceedMaxActive', 'mustHaveBudget'])
: subscriptionGate(['mustIncludeService']),
],
tool: defineTool({
name: 'activate-campaign',
description: 'Activate or deactivate a campaign.',
inputSchema: z.object({ isActive: z.boolean() }),
method: ({ userId, isActive }) => toggleCampaign(userId, isActive),
}),
}),
],
});