Build a server
A complete Mayfain MCP server in TypeScript, step by step.
This guide builds a complete Mayfain MCP server for one business, in TypeScript. It uses the trades template (an electrician) as the example; every template works the same way. The steps that need a Preview endpoint are marked.
What you'll end up with: one HTTPS endpoint that speaks MCP (Streamable HTTP, JSON responses), answers public tools for any agent, accepts private tools only with a valid Mayfain token, and writes requests into the business's own systems.
Aim for useful, not many. Implement the template's tools the business can really support, and wire each one to real data: live availability from the calendar, real prices, real job status. Don't add tools for the sake of it; every tool should save the person or the business a real step. Write each description so an agent knows exactly when to use it.
Before you start
You need:
- The business's website, and access to the systems you already run for it (job software such as Jobber, Simpro or ServiceM8; a calendar; a CRM; or just its inbox).
- Node.js 20 or later.
- From Mayfain, when your server is registered: a
client_idandclient_secretfor introspection and the Mayfain API.
mkdir byrne-electrical-mcp && cd byrne-electrical-mcp
npm init -y
npm install jose zod
npm install -D typescript @types/node tsx
1. Pick the template
Read the business's website and pick the template for what it does:
| The business… | Template |
|---|---|
| Lets or sells homes | rentals, sales (Live) |
| Visits a site to do a job: electrician, plumber, heating, locksmith, cleaner | trades (Preview) |
| Sells an ongoing plan with an account: broadband, energy | broadband (Demo) |
The templates reference lists every tool, its action, tier, scopes and input schema. Copy them exactly.
2. Configuration
// src/config.ts
export const config = {
// Your server's canonical URL. It must equal the token's `aud`, character for character.
resource: process.env.RESOURCE_URL ?? "https://mcp.byrne-electrical.ie/mcp",
mayfain: "https://mayfain.ie",
clientId: process.env.MAYFAIN_CLIENT_ID!,
clientSecret: process.env.MAYFAIN_CLIENT_SECRET!,
vertical: "trades",
};
3. Define the tools from the template
The trades template is Preview, so its tool names may still change. Each tool carries Mayfain's tags in _meta, plus honest MCP annotations. Descriptions are in the business's own words; tool names, actions, tiers and scopes come from the template.
// src/tools.ts
import { z } from "zod";
type Tool = {
name: string;
capability: string;
policyClass: "read" | "write" | "sensitive";
public: boolean;
requiredScopes: string[];
description: string;
input: z.ZodObject<z.ZodRawShape>;
inputSchema: Record<string, unknown>; // JSON Schema shown in tools/list
};
export const TOOLS: Tool[] = [
{
name: "check_service_area",
capability: "get_requirements",
policyClass: "read",
public: true,
requiredScopes: [],
description: "Check whether Byrne Electrical covers an area. Accepts an Eircode routing key such as D09.",
input: z.object({ area: z.string().min(2).max(10) }),
inputSchema: {
type: "object",
properties: { area: { type: "string", description: "Eircode routing key, e.g. D09" } },
required: ["area"],
},
},
{
name: "request_job",
capability: "submit",
policyClass: "sensitive",
public: false,
requiredScopes: ["applications.write", "profile.basic"],
description:
"Ask Byrne Electrical to do a job for the signed-in person. Their name, phone and address come from Mayfain; " +
"don't send them. Only send the problem in the person's own words and when they're free.",
input: z.object({
service: z.enum(["fault_finding", "sockets_and_lights", "ev_charger", "fuse_board"]),
description: z.string().max(2000),
urgency: z.enum(["emergency", "this_week", "flexible"]),
preferred_times: z.array(z.object({ start: z.string(), end: z.string() })).max(5).default([]),
}),
inputSchema: { /* the JSON Schema of the input above */ },
},
// …every other tool in the template
];
export function toolDefinition(t: Tool) {
return {
name: t.name,
description: t.description,
inputSchema: t.inputSchema,
annotations: { readOnlyHint: t.policyClass === "read", destructiveHint: false, openWorldHint: false },
_meta: {
"mayfain.ie/vertical": "trades",
"mayfain.ie/capability": t.capability,
"mayfain.ie/policyClass": t.policyClass,
"mayfain.ie/public": t.public,
"mayfain.ie/requiredScopes": t.requiredScopes,
},
};
}
Never put personal fields (name, phone, address, ID) in a tool's input. Those come from Mayfain, verified, in step 6.
4. Check the token
Use the code from Authentication, plus introspection for tools that change something:
// src/auth.ts
import { createRemoteJWKSet, jwtVerify } from "jose";
import { config } from "./config";
const JWKS = createRemoteJWKSet(new URL(`${config.mayfain}/.well-known/jwks.json`), { cacheMaxAge: 600_000 });
const basic = () => "Basic " + Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64");
const metadata = `${new URL(config.resource).origin}/.well-known/oauth-protected-resource`;
export type Claims = { sub: string; scope: string; grant_id: string; client_id: string; jti: string };
export class AuthError extends Error {
constructor(public status: 401 | 403, public challenge: string) {
super("unauthorised");
}
}
export async function requireToken(header: string | null, scopes: string[], live: boolean): Promise<Claims> {
const scope = `scope="${scopes.join(" ")}"`;
const token = /^Bearer\s+(\S+)$/i.exec(header ?? "")?.[1];
if (!token) throw new AuthError(401, `Bearer resource_metadata="${metadata}", ${scope}`);
let claims: Claims;
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: config.mayfain,
audience: config.resource,
algorithms: ["ES256"],
});
claims = payload as unknown as Claims;
} catch {
throw new AuthError(401, `Bearer error="invalid_token", resource_metadata="${metadata}", ${scope}`);
}
const granted = new Set(claims.scope.split(" "));
if (scopes.some((s) => !granted.has(s)))
throw new AuthError(403, `Bearer error="insufficient_scope", resource_metadata="${metadata}", ${scope}`);
if (live) {
const r = await fetch(`${config.mayfain}/oauth/introspect`, {
method: "POST",
headers: { authorization: basic(), "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token }),
});
const body = (await r.json()) as { active?: boolean };
if (!body.active) throw new AuthError(401, `Bearer error="invalid_token", resource_metadata="${metadata}", ${scope}`);
}
return claims;
}
5. Serve MCP over HTTP
A stateless Streamable HTTP endpoint with JSON responses: one POST per JSON-RPC message, no sessions. This handler uses web-standard Request and Response, so it runs on Node, Vercel, Cloudflare Workers, Deno and Bun. You can use the official MCP SDK instead; the Mayfain parts (tool definitions, token check, adapters) stay the same.
// src/server.ts
import { TOOLS, toolDefinition } from "./tools";
import { AuthError, requireToken } from "./auth";
import { config } from "./config";
import { handlers } from "./handlers";
const VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"];
const rpc = (id: unknown, result: unknown) => Response.json({ jsonrpc: "2.0", id, result });
const rpcError = (id: unknown, code: number, message: string) => Response.json({ jsonrpc: "2.0", id, error: { code, message } });
export async function handle(req: Request): Promise<Response> {
const url = new URL(req.url);
if (req.method === "GET" && url.pathname === "/.well-known/oauth-protected-resource")
return Response.json({
resource: config.resource,
authorization_servers: [config.mayfain],
scopes_supported: [...new Set(TOOLS.flatMap((t) => t.requiredScopes))],
bearer_methods_supported: ["header"],
});
if (req.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST" } });
const msg = (await req.json()) as { id?: unknown; method: string; params?: any };
switch (msg.method) {
case "initialize": {
const asked = msg.params?.protocolVersion;
return rpc(msg.id, {
protocolVersion: VERSIONS.includes(asked) ? asked : VERSIONS[0],
capabilities: { tools: {} },
serverInfo: { name: "byrne-electrical", title: "Byrne Electrical", version: "1.0.0" },
});
}
case "notifications/initialized":
return new Response(null, { status: 202 });
case "ping":
return rpc(msg.id, {});
case "tools/list":
return rpc(msg.id, { tools: TOOLS.map(toolDefinition) });
case "tools/call": {
const tool = TOOLS.find((t) => t.name === msg.params?.name);
if (!tool) return rpcError(msg.id, -32602, `Unknown tool: ${msg.params?.name}`);
const args = tool.input.safeParse(msg.params?.arguments ?? {});
if (!args.success) return rpc(msg.id, { isError: true, content: [{ type: "text", text: args.error.message }] });
let claims = null;
if (!tool.public) {
try {
claims = await requireToken(req.headers.get("authorization"), tool.requiredScopes, tool.policyClass !== "read");
} catch (e) {
if (e instanceof AuthError)
return new Response(null, { status: e.status, headers: { "www-authenticate": e.challenge } });
throw e;
}
}
const result = await handlers[tool.name]!(args.data, claims);
return rpc(msg.id, { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result });
}
default:
return rpcError(msg.id, -32601, `Method not found: ${msg.method}`);
}
}
6. Write the handlers
Handlers connect the template to the business's systems. Public handlers return only non-personal data. Private handlers fetch the verified details from Mayfain (Preview), then create the job.
// src/handlers.ts
import { config } from "./config";
import type { Claims } from "./auth";
import { jobs, serviceArea } from "./adapters"; // your code for Jobber, Simpro, ServiceM8, the inbox…
const basic = () => "Basic " + Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64");
export const handlers: Record<string, (args: any, claims: Claims | null) => Promise<Record<string, unknown>>> = {
async check_service_area({ area }) {
const covered = serviceArea.includes(area.toUpperCase());
return { covered, callout_fee_eur: covered ? 95 : null };
},
async request_job(args, claims) {
// Preview: the verified details the person approved for this request, each labelled.
const r = await fetch(`${config.mayfain}/v1/submissions`, {
method: "POST",
headers: { authorization: basic(), "content-type": "application/json" },
body: JSON.stringify({
grant_id: claims!.grant_id,
sub: claims!.sub,
stage: "applied",
offer: { ref: args.service, title: "Electrical job" },
submitted: { message: args.description, urgency: args.urgency, preferred_times: args.preferred_times },
}),
});
if (!r.ok) return { status: "declined", message: "We couldn't take this request right now." };
const sub = (await r.json()) as {
submission_id: string;
profile: { full_name: { value: string; label: string }; phone: { value: string; label: string }; address: { value: string; label: string } };
};
const job = await jobs.create({
customer: sub.profile.full_name.value,
phone: sub.profile.phone.value,
address: sub.profile.address.value,
notes: args.description,
urgency: args.urgency,
mayfainSubmission: sub.submission_id,
mayfainSubject: claims!.sub,
});
// Don't make the agent wait for a human at the business: acknowledge now, reply later through the API.
return { request_id: job.id, status: "acknowledged", message: "Byrne Electrical will reply with times." };
},
};
Rules for handlers:
- Never trust personal data from tool arguments. It comes from Mayfain, verified and labelled.
- Store the pairwise
suband your own request ID. Never store the token. - Keep only what the business needs to do the job.
- If the business has to decide something (a quote after seeing photos), return
acknowledgedstraight away and follow up with a message.
7. Reply to the person
When the business answers, your existing automation calls Mayfain (Preview). Mayfain delivers it to the person by push, email or text, and can show choices as buttons.
await fetch(`https://mayfain.ie/v1/submissions/${submissionId}/messages`, {
method: "POST",
headers: { authorization: basic(), "content-type": "application/json" },
body: JSON.stringify({
text: "Thanks Aoife. We can come Thursday morning or Friday afternoon.",
ask: {
type: "choose_slot",
options: [
{ id: "s1", start: "2026-10-22T09:00:00+01:00", end: "2026-10-22T11:00:00+01:00" },
{ id: "s2", start: "2026-10-23T14:00:00+01:00", end: "2026-10-23T16:00:00+01:00" },
],
},
}),
});
See Mayfain API for status updates and answers.
8. Run it
// src/index.ts (Node; on Vercel, Cloudflare or Deno export `handle` instead)
import { createServer } from "node:http";
import { handle } from "./server";
createServer(async (req, res) => {
const body = req.method === "POST" ? await new Promise<string>((ok) => { let b = ""; req.on("data", (c) => (b += c)); req.on("end", () => ok(b)); }) : undefined;
const r = await handle(new Request(`http://localhost${req.url}`, { method: req.method, headers: req.headers as any, body }));
res.writeHead(r.status, Object.fromEntries(r.headers));
res.end(await r.text());
}).listen(8787);
npx tsx src/index.ts
Then work through Going live.