@flipdish/mcp-sdk
v0.3.0
Published
Define a service's MCP tools once: serve them at the service's MCP route and emit the manifest the flipdish-mcp gateway reads
Keywords
Readme
@flipdish/mcp-sdk
Define a service's MCP tools once. The SDK serves them at the service's MCP route and emits the
<service>.mcp-manifest.json the flipdish-mcp gateway (mcp.flipdish.com) reads to advertise
them and route their calls (EDR-96). Both come from the same definitions, so the endpoint and the
manifest cannot drift.
Installation
pnpm add @flipdish/mcp-sdkThe package bundles its own zod 4 and MCP server SDK, and no zod type is part of its API, so it
works alongside a service still on zod 3. @types/aws-lambda is an optional peer, needed for the
types of @flipdish/mcp-sdk/aws-lambda; aws-cdk-lib and constructs are optional peers, needed
only for @flipdish/mcp-sdk/cdk.
Define the tools
import { defineMcpService, input, McpToolError } from '@flipdish/mcp-sdk';
export const reportMcp = defineMcpService({
service: 'report-builder',
team: 'reporting',
version: '1.0.0',
routeTemplate: '/mcp/orgs/{orgId}/brands/{brandId}',
timeoutMs: 28_000,
featureFlag: 'backend_reporting_reportBuilderMcp',
// Built once per tools/call, from the route params and headers; pass `signal` to upstream calls.
context: (request) => ({ tenant: { orgId: request.orgId, brandId: request.brandId }, translate: translator(request.acceptLanguage) }),
// Model-visible text for an expected error; undefined logs it and answers a generic message.
mapError: (error, call) => (error instanceof ReportNotFoundError ? call.context.translate('Report_not_found') : undefined),
// Optional: wraps every call, e.g. in a tracing span.
aroundToolCall: (call, run) => tracer.trace(`report-mcp.${call.tool}`, run),
tools: (tool) => [
tool({
name: 'get_report',
description: 'Shows one saved report. orgId comes from get_orgs, brandId from get_brands, reportId from list_reports.',
readOnly: true,
input: {
reportId: input.string({ description: 'The ReportId from list_reports (e.g. "weekly-sales").', minLength: 1, maxLength: 100 }),
scope: input.enum(['private', 'brand', 'org'], { description: 'Who can see it: "private", "brand" or "org".' }).optional(),
},
handler: async ({ reportId }, { context, request, signal }) => formatReport(await getReport(reportId, context.tenant, signal)),
}),
],
});- Inputs are flat scalars:
input.string,input.enum,input.number,input.integerandinput.boolean, each optionally.optional(). Each one is the JSON Schema property the manifest advertises, andtools/callvalidates against that same schema, converted the way the gateway converts it. Plain-decimal text for a number,"true"/"false"for a boolean and a plain number for a string are accepted;"","1e3"and"yes"are not.trim: truetrims a string before its length is checked. - orgId and brandId come from the route, never from
input(a type error and a runtime error).request.brandIdis astringwhen the route template has{brandId}. If a single service mixes org-scoped and brand-scoped tools, setrouteTemplateon the tools that need a different route so the service still publishes one manifest. request.tokenis the caller's Flipdish token (theFD-Authorizationheader the gateway sends, else theAuthorizationbearer), for calls made on their behalf. Never log it.- Results: return a string, or
{ content: [{ type: 'text', text }] };json(value)builds indented JSON text. ThrowMcpToolError('…')for a failure the model may read. Anything else is logged and answered with a generic message, which for a write tool tells the model the change may have saved. - Invalid arguments come back as a tool error (
isError: true) naming each argument, the problem, and the argument's description, so the model can retry. - The definitions are checked with the gateway's own validator when
defineMcpServiceruns: a snake_case name, no duplicate, no legacy term (store ID, app ID, white label, …) in a name, title, description, input or theinstructions. A result, or anMcpToolErrorormapErrormessage, carrying a legacy identifier (storeId,appId, …) is logged and replaced with the generic failure, since the gateway would fail that call anyway. Ordinary words ("franchisee") pass, as at the gateway, since they can be user-written text.
Serve the route
On an API Gateway HTTP API (payload 2.0):
import { toApiGatewayHandler } from '@flipdish/mcp-sdk/aws-lambda';
export const handler = toApiGatewayHandler(reportMcp);Route POST <routeTemplate> to it behind the service's authorizer: the SDK checks no permission.
Each handler's signal aborts 3 seconds (responseReserveMs) before the Lambda times out, and the
call answers a "ran out of time" tool error then, even if the handler ignores the signal (pass it
on to upstream calls so the work stops too). Elsewhere, reportMcp.fetch(request) serves a Fetch API
Request; the route params are read from the end of the URL path.
The endpoint is stateless Streamable HTTP with JSON responses, which is what the gateway sends: a
tools/call with no initialize first. Direct MCP clients on the 2025 or 2026-07-28 protocol work
too.
Publish the manifest
Pass the service's public base URLs for the shared stages. mcpManifestTarget picks the gateway
bucket, the base URL and allowExecuteApi for the deploy stage. An ephemeral stage uploads only
when both MCP_MANIFEST_BUCKET and a literal MCP_MANIFEST_BASE_URL are set.
import { McpManifestDeployment, mcpManifestTarget } from '@flipdish/mcp-sdk/cdk';
const target = mcpManifestTarget({
stage: app.stage,
baseUrls: {
production: 'https://api.flipdish.co/report-builder',
'prod-staging': 'https://api-prod-staging.portal.flipdishdev.com/report-builder',
},
});
if (target) {
new McpManifestDeployment(stack, 'McpManifest', {
bucketName: target.bucketName,
manifest: reportMcp.manifest({ baseUrl: target.baseUrl, allowExecuteApi: target.allowExecuteApi }),
serviceEndpoint: api,
});
}manifest() validates with @flipdish/mcp-manifest and throws McpManifestError listing every
issue. allowExecuteApi is false on production only. The base URL must be a literal string.
Do not pass an unresolved CDK token.
The construct puts <service>.mcp-manifest.json with s3:PutObject on that one key, after
serviceEndpoint deploys. The gateway's bucket policy accepts writes from any role in Flipdish's
AWS Organization.
Removing the construct or the stack does not retire the tools. Nothing can delete the object
from a service account. The gateway keeps advertising a manifest until its object is deleted
(ADR-0008). To retire a service, ask the flipdish-mcp owners to delete <service>.mcp-manifest.json
from each stage's bucket.
Two checks only the gateway runs: featureFlag must be registered in its Split filter, and a raw
API Gateway host is accepted only on non-production gateway stages.
Test
const result = await reportMcp.callTool('get_report', { reportId: 'weekly-sales' }, { orgId: 'org123', brandId: 'br456' });callTool runs a tool as tools/call would (validation, context, error mapping), without HTTP.
