# Mayfain builder docs

---



---

Source: https://mayfain.ie/docs. Generated from the same files as the site. Live templates are generated from the running code.

---



---

# Overview

Mayfain lets people hand their life admin to an AI agent: renting a home, booking a tradesperson, switching broadband, renewing insurance. The agent can be Mayfain's own, or one the person already uses in ChatGPT or Claude. It reaches each business through **that business's MCP server**.

These docs are for whoever builds that server: a company building AI for businesses, a business's own team, or the coding agent they work with.

> **If you are an AI agent:** the whole documentation is one Markdown file at [`/docs.md`](https://mayfain.ie/docs.md). Read it top to bottom before writing code. The index is at [`/llms.txt`](/llms.txt).

## Your goal

**Let a person get as much done with this business as possible, through their agent, without picking up the phone.**

Build the tools in the business's template that it can really support, and make each one genuinely useful: accurate data, real availability, honest prices, clear descriptions. More tools isn't the aim; useful ones are. Each tool should save the person or the business a real step (finding, comparing, asking, booking, rescheduling, messaging, sending documents, checking status). A tool that only says "call us" helps nobody.

If the business does something people would want to do that the template doesn't cover yet, tell us. We add it to the template, so every business in the vertical gets it and every agent can use it the same way.

## What Mayfain does, and what your server does

| Mayfain | Your server |
|---|---|
| Verifies the person (ID, income, documents) and keeps their details in an encrypted vault | Exposes the business's actions as MCP tools, using the vertical's template |
| Records the person's consent, and shows them exactly what will be sent | Answers public questions (listings, plans, slots, prices) for any agent |
| Acts as the OAuth authorization server and signs the access tokens | Accepts private calls only with a valid Mayfain token for this server |
| Gives you verified details, each labelled, only after the person approves | Writes requests into the business's real systems (job software, CRM, inbox) |

The model never sees the person's sensitive values and never holds a token. Nothing is sent to a business without the person's explicit approval.

## How a request flows

```
person ──▶ agent ──▶ your MCP server ──▶ the business's systems
              │            ▲      │
              │   signed   │      │  grant_id + sub (your own credentials)
              ▼   token    │      ▼
            Mayfain  (vault, consent, authorization server)
```

1. The person asks their agent for something ("book an electrician this week").
2. The agent calls your **public** tools to compare: coverage, availability, prices.
3. The person picks you and approves what will be sent, on Mayfain.
4. Mayfain issues a short-lived token for your server, and the **private** tool is called with it.
5. Your server checks the token, then fetches the verified details from Mayfain with its own credentials, and creates the request in the business's systems.

## Status

Everything on these pages is labelled **Live** or **Preview**.

| Part | Status |
|---|---|
| Templates: rentals, sales | Live, on servers Mayfain hosts |
| Access tokens, public keys (JWKS), authorization server metadata | Live |
| Token introspection | Live |
| Servers run by partners, end to end | Preview: founding partners, onboarded with us |
| Submissions, messages and status APIs for partner servers | Preview |
| Template: trades and home services | Preview |
| Template: broadband | Demo providers only |

Preview means the contract is written and may still change. [Become a partner](/partners#apply) to build against it with us.

## Read next

- [Concepts](https://mayfain.ie/docs/concepts): actions, tiers, scopes, labels and templates.
- [Authentication](https://mayfain.ie/docs/authentication): the token and how to check it.
- [Build a server](https://mayfain.ie/docs/build): step by step, with full code.
- [Templates reference](https://mayfain.ie/docs/reference): every tool, generated from the live templates.
- [Mayfain API](https://mayfain.ie/docs/api): the endpoints your server calls.
- [Going live](https://mayfain.ie/docs/go-live): the checks every server passes.


---

# Concepts

## Templates

A **template** defines one vertical: the tool names, their inputs and outputs, the scopes each needs, and the action each performs. Every business in a vertical exposes the same template, so one person's agent can use thousands of businesses without learning each one. A new vertical is a new template, not a new product.

Don't rename tools, change their actions or change their tiers. You write the descriptions in the business's own words, fill the data, and connect the adapters to the business's systems.

## Actions

Every tool maps to one **action** (`capability` in the code). The action, not the tool name, is how Mayfain and agents know what a tool does.

| Action | Usual tier | What it does |
|---|---|---|
| `search_offers` | public | What the business offers: listings, plans, services. Filters only, no personal data. |
| `get_offer` | public | One offer in full. |
| `get_requirements` | public | What a person needs to apply or order, and which checks the business asks for. |
| `get_quote` | private | A price that needs something private, such as an Eircode, shared with consent. |
| `submit` | private | Apply, order or request a service for the person. |
| `get_status` | private | Where one of the person's requests stands. |
| `list_mine` | private | The person's requests with this business. |
| `withdraw` | private | The person withdraws a request. |
| `send_message` | private | A message from the person, in their own words, about an existing request. |
| `list_slots` | private | Times the business can offer (viewings, visits, appointments). |
| `book_slot` | private | The person books one of those times. |
| `cancel_slot` | private | The person cancels a booked time. |

A template can make a usually-public action private (rentals keeps viewing slots private). It never goes the other way.

## Tiers: public and private

- **Public** tools work without a token, for any agent. No personal data goes in or comes out.
- **Private** tools act for one person. They need a Mayfain access token issued for your server, carrying the scopes the tool requires.

## Policy classes

Each tool also has a **policy class**, which tells agents and Mayfain how careful to be:

| Class | Meaning | MCP annotation |
|---|---|---|
| `read` | Reads only | `readOnlyHint: true` |
| `write` | Changes something for the person | `readOnlyHint: false` |
| `sensitive` | Sends the person's verified details | `readOnlyHint: false` |

For `write` and `sensitive` tools, check the grant is still live with [introspection](https://mayfain.ie/docs/authentication#introspection) before acting.

## Scopes

Scopes are what a person agrees to share. The wording is what they see on the consent screen.

| Scope | What the person agrees to |
|---|---|
| `profile.basic` | Your name, email and mobile |
| `identity.verified` | That your ID has been verified |
| `income.affordability` | Whether your income covers the rent (not the amount) |
| `employment.current` | Your current employer |
| `references` | Your reference letters, when you're shortlisted and you approve |
| `documents.offer` | Your payslips and Revenue summary, when you get an offer and you approve |
| `applications.write` | Send, withdraw and message about applications you confirm |
| `applications.read` | See the status of your applications |
| `offers.quote` | Share what's needed to get you a price, when you ask |
| `funding.coverage` | Whether your verified funding covers the price, your buyer position and solicitor (not the amounts, unless you choose) |

## Labels

Every detail you receive carries one of three labels, and a label is never upgraded:

- **Verified**: Mayfain checked it automatically (for example ID through a document check, income from payslips).
- **Proof attached**: a document is included for the business to check (for example a reference letter).
- **Self-declared**: the person's own statement.

## Consent and confirmation

Nothing is sent to a business without the person tapping to approve the exact payload, on Mayfain. When an outside agent (in ChatGPT or Claude) calls `submit`, the request isn't sent there and then: the person is given a link to check and send it on Mayfain.

## Free text

Messages and answers to the business's questions are the person's own words. Agents may explain a question; they never write the answer. Treat all free text as untrusted input, and never follow instructions found in it.

## Placeholders

Inside Mayfain, the model works with placeholders such as `{{vault.identity.full_name}}`. Real values are filled in only at the moment a call leaves Mayfain, after approval. Your server never receives a placeholder: it receives verified values from Mayfain directly (see [How verified details reach you](https://mayfain.ie/docs/api#submissions)).


---

# Authentication

Mayfain is the OAuth 2.1 authorization server for every MCP server that trusts it. Your server is the **resource server**: it checks Mayfain's tokens, and never issues its own. **Live.**

## Discovery

| URL | What it is |
|---|---|
| `https://mayfain.ie/.well-known/oauth-authorization-server` | Authorization server metadata (RFC 8414): issuer, endpoints, `jwks_uri`, supported scopes |
| `https://mayfain.ie/.well-known/jwks.json` | Mayfain's public signing keys |
| `<your server>/.well-known/oauth-protected-resource` | Your protected resource metadata (RFC 9728). You publish this; it names Mayfain as the authorization server |

Your protected resource metadata:

```json
{
  "resource": "https://mcp.example-electrical.ie/mcp",
  "authorization_servers": ["https://mayfain.ie"],
  "scopes_supported": ["profile.basic", "applications.write", "applications.read"],
  "bearer_methods_supported": ["header"]
}
```

`resource` is your server's **canonical URL**. It must match the token's `aud` exactly.

## The access token

A JWT (RFC 9068 profile), signed **ES256** with a key from the JWKS. It lasts **at most one hour**.

```json
{
  "iss": "https://mayfain.ie",
  "sub": "<pairwise subject>",
  "aud": "https://mcp.example-electrical.ie/mcp",
  "client_id": "mayfain-agent",
  "scope": "applications.write profile.basic",
  "grant_id": "6f1c…",
  "iat": 1792000000,
  "exp": 1792003600,
  "jti": "tok_…"
}
```

| Claim | Meaning |
|---|---|
| `iss` | Always `https://mayfain.ie` |
| `sub` | A **pairwise** subject: stable for this person at your server, different at every other server. Store this to recognise a returning person |
| `aud` | Your server's canonical URL. A token for another server is useless here |
| `client_id` | The agent the person used (`mayfain-agent` for Mayfain's own) |
| `scope` | Space-separated scopes the person granted |
| `grant_id` | The person's grant to your business. Use it with `sub` when you call Mayfain |
| `exp` | Expiry, at most an hour after `iat` |
| `jti` | The token's ID |

Never forward the token to any other service, and never store it.

## Checking a token

On every private tool call:

1. Read `Authorization: Bearer <token>`. If it's missing, return **401** (below).
2. Verify the signature against the JWKS (cache the keys for 10 minutes). Only accept `ES256`.
3. Check `iss` is `https://mayfain.ie`, `aud` is your canonical URL, and `exp` is in the future.
4. Check the token's `scope` contains every scope the tool requires. If not, return **403**.
5. For `write` and `sensitive` tools, call [introspection](#introspection) and refuse unless `active` is `true`. A person can withdraw permission at any time, and introspection makes that instant.

```ts
import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(new URL("https://mayfain.ie/.well-known/jwks.json"), {
  cacheMaxAge: 10 * 60 * 1000,
});

export async function verifyMayfainToken(token: string, resource: string) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: "https://mayfain.ie",
    audience: resource,
    algorithms: ["ES256"],
  });
  return payload as {
    sub: string; aud: string; scope: string; grant_id: string; client_id: string; exp: number; jti: string;
  };
}
```

## Errors

No token, or a bad one:

```http
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example-electrical.ie/.well-known/oauth-protected-resource",
                  scope="applications.write profile.basic"
```

A valid token without enough scope:

```http
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", scope="applications.write profile.basic",
                  resource_metadata="https://mcp.example-electrical.ie/.well-known/oauth-protected-resource"
```

Agents that support MCP authorization read `resource_metadata`, find Mayfain, and send the person to sign in and approve. ChatGPT also reads the same challenge from a tool result: return an error result with `_meta["mcp/www_authenticate"] = [<the header value>]`.

## Introspection

**Live.** `POST https://mayfain.ie/oauth/introspect` (RFC 7662), with your server's own credentials.

```http
POST /oauth/introspect HTTP/1.1
Host: mayfain.ie
Authorization: Basic base64(<client_id>:<client_secret>)
Content-Type: application/x-www-form-urlencoded

token=<the access token>
```

```json
{
  "active": true,
  "grant_id": "6f1c…",
  "scope": "applications.write profile.basic",
  "sub": "<pairwise subject>",
  "client_id": "mayfain-agent",
  "exp": 1792003600,
  "aud": "https://mcp.example-electrical.ie/mcp",
  "iss": "https://mayfain.ie",
  "token_type": "Bearer"
}
```

`active: false` means the grant was withdrawn, has expired, or the token isn't for your business. Refuse the call.

Your `client_id` and `client_secret` are issued by Mayfain when your server is registered. Keep them on the server only.


---

# Build a server

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_id` and `client_secret` for introspection and the Mayfain API.

```bash
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](https://mayfain.ie/docs/reference) lists every tool, its action, tier, scopes and input schema. Copy them exactly.

## 2. Configuration

```ts
// 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.

```ts
// 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](https://mayfain.ie/docs/authentication#checking-a-token), plus introspection for tools that change something:

```ts
// 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.

```ts
// 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.

```ts
// 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 `sub` and 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 `acknowledged` straight away and follow up with a [message](https://mayfain.ie/docs/api#messages).

## 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.

```ts
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](https://mayfain.ie/docs/api) for status updates and answers.

## 8. Run it

```ts
// 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);
```

```bash
npx tsx src/index.ts
```

Then work through [Going live](https://mayfain.ie/docs/go-live).


---

# Templates reference

Every tool in every template. The live templates below are generated from the code Mayfain runs, so they're always current. Use the names, actions, tiers, scopes and input schemas exactly as written.

## Rentals

**Live.** Letting agents: listings, requirements, applications, viewings and messages.

### `search_listings`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `search_offers` | public | `read` | none |

Search this agency's available rental listings. Public: no personal data needed.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "area": {
      "type": "string"
    },
    "max_rent_eur": {
      "type": "number"
    },
    "min_beds": {
      "type": "integer"
    },
    "pets": {
      "type": "boolean"
    },
    "available_by": {
      "type": "string",
      "format": "date"
    }
  },
  "additionalProperties": false
}
```

### `get_listing`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `get_offer` | public | `read` | none |

Get full details of one listing.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "listing_id": {
      "type": "string"
    }
  },
  "required": [
    "listing_id"
  ],
  "additionalProperties": false
}
```

### `get_requirements`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `get_requirements` | public | `read` | none |

What this listing needs from an applicant: verified claims, questions the applicant must answer in their own words, and which documents are requested at which stage.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "listing_id": {
      "type": "string"
    }
  },
  "required": [
    "listing_id"
  ],
  "additionalProperties": false
}
```

### `submit_application`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `submit` | private | `sensitive` | `applications.write`, `profile.basic`, `identity.verified`, `income.affordability`, `employment.current` |

Submit an application for the signed-in person. Verified identity, income and employment are fetched by the agency directly from Mayfain; do not send them. Only send the person's own answers and message, written by them.

Free text, in the person's own words: `message`, `answers.*`.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "listing_id": {
      "type": "string"
    },
    "message": {
      "type": "string",
      "maxLength": 2000
    },
    "answers": {
      "type": "object",
      "additionalProperties": {
        "type": "string"
      },
      "default": {}
    },
    "move_in_date": {
      "type": "string",
      "format": "date"
    },
    "adults": {
      "type": "integer"
    },
    "children": {
      "type": "integer"
    },
    "pets": {
      "type": "string"
    },
    "co_application_id": {
      "type": "string"
    },
    "joint_summary_sha256": {
      "type": "string"
    },
    "referee_contact": {
      "type": "object",
      "properties": {
        "contact": {
          "type": "string"
        },
        "note": {
          "type": "string"
        }
      },
      "required": [
        "contact"
      ],
      "additionalProperties": false
    }
  },
  "required": [
    "listing_id"
  ],
  "additionalProperties": false
}
```

### `get_application_status`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `get_status` | private | `read` | `applications.read` |

Status of one of the person's applications.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "application_id": {
      "type": "string"
    }
  },
  "required": [
    "application_id"
  ],
  "additionalProperties": false
}
```

### `list_my_applications`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `list_mine` | private | `read` | `applications.read` |

The signed-in person's applications with this agency.

Input schema:

```json
{
  "type": "object",
  "properties": {},
  "additionalProperties": false
}
```

### `withdraw_application`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `withdraw` | private | `write` | `applications.write` |

Withdraw one of the person's applications.

Free text, in the person's own words: `reason`.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "application_id": {
      "type": "string"
    },
    "reason": {
      "type": "string"
    }
  },
  "required": [
    "application_id"
  ],
  "additionalProperties": false
}
```

### `send_message`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `send_message` | private | `write` | `applications.write` |

Send a message from the person to the agency about an application. The body must be the person's own words.

Free text, in the person's own words: `body`.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "application_id": {
      "type": "string"
    },
    "body": {
      "type": "string",
      "maxLength": 4000
    }
  },
  "required": [
    "application_id",
    "body"
  ],
  "additionalProperties": false
}
```

### `list_viewing_slots`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `list_slots` | private | `read` | `applications.write` |

Viewing times the agency offered this person for a listing, and the one they've booked, if any.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "listing_id": {
      "type": "string"
    }
  },
  "required": [
    "listing_id"
  ],
  "additionalProperties": false
}
```

### `book_viewing`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `book_slot` | private | `write` | `applications.write`, `profile.basic` |

Book one of the viewing times the agency offered the signed-in person.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "listing_id": {
      "type": "string"
    },
    "slot_id": {
      "type": "string"
    }
  },
  "required": [
    "listing_id",
    "slot_id"
  ],
  "additionalProperties": false
}
```

### `cancel_viewing`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `cancel_slot` | private | `write` | `applications.write` |

Cancel the signed-in person's booked viewing for a listing.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "listing_id": {
      "type": "string"
    }
  },
  "required": [
    "listing_id"
  ],
  "additionalProperties": false
}
```

## Sales

**Live.** Estate agents. Listings, requirements, viewings and messages use the same tools as rentals; sales adds the buyer's application, which carries verified funding coverage (never the amounts unless the buyer chooses).

### `submit_purchase_application`

| Action | Tier | Class | Scopes |
|---|---|---|---|
| `submit` | private | `sensitive` | `applications.write`, `profile.basic`, `identity.verified`, `funding.coverage` |

Send a verified buyer pack for a property for sale, for the signed-in person. Verified ID, address and whether their verified funding covers the agent's threshold are fetched by the agency directly from Mayfain; never the amounts. Only send the person's own message, written by them.

Free text, in the person's own words: `message`.

Input schema:

```json
{
  "type": "object",
  "properties": {
    "listing_id": {
      "type": "string"
    },
    "message": {
      "type": "string",
      "maxLength": 2000
    },
    "share_aip_amount": {
      "type": "boolean",
      "default": false
    },
    "co_application_id": {
      "type": "string"
    },
    "joint_summary_sha256": {
      "type": "string"
    }
  },
  "required": [
    "listing_id"
  ],
  "additionalProperties": false
}
```

## Trades and home services

**Preview.** Electricians, plumbers, heating engineers, locksmiths, cleaners. The contract founding partners build against; names may change. See [Build a server](https://mayfain.ie/docs/build) for a worked example.

| Tool | Action | Tier | Scopes | What it does |
|---|---|---|---|---|
| `list_services` | `search_offers` | public | none | Services the business offers, with typical prices and durations. |
| `get_service` | `get_offer` | public | none | One service in full. |
| `check_service_area` | `get_requirements` | public | none | Whether the business covers an area (Eircode routing key), and its call-out fee. |
| `get_quote` | `get_quote` | private | `offers.quote` | An indicative price that needs the person's address, shared with consent. |
| `request_job` | `submit` | private | `applications.write`, `profile.basic` | Ask for a job: the problem in the person's words, urgency and when they're free. Contact details come from Mayfain. |
| `get_job_status` | `get_status` | private | `applications.read` | Where one of the person's jobs stands. |
| `list_my_jobs` | `list_mine` | private | `applications.read` | The person's jobs with this business. |
| `cancel_job` | `withdraw` | private | `applications.write` | The person cancels a job request. |
| `send_message` | `send_message` | private | `applications.write` | A message from the person about an existing job, in their own words. |
| `list_visit_slots` | `list_slots` | private | `applications.write` | Times the business can visit. |
| `book_visit` | `book_slot` | private | `applications.write`, `profile.basic` | The person books one of those times. |
| `cancel_visit` | `cancel_slot` | private | `applications.write` | The person cancels a booked visit. |

## Broadband

**Demo.** Plans by address and quotes, with demo providers only. No real orders yet.

---

# Mayfain API

The HTTP endpoints your server calls. All are on `https://mayfain.ie`. Requests from your server authenticate with your `client_id` and `client_secret` (HTTP Basic). Never call these from a browser or put the secret in front-end code.

| Endpoint | Status |
|---|---|
| `GET /.well-known/oauth-authorization-server` | Live |
| `GET /.well-known/jwks.json` | Live |
| `POST /oauth/introspect` | Live |
| `POST /v1/submissions` | Preview |
| `POST /v1/submissions/{id}/messages` | Preview |
| `POST /v1/submissions/{id}/status` | Preview |
| Webhooks to your server | Preview |

Preview endpoints are the contract founding partners build against with us. They may change before general release.

## Introspection

**Live.** See [Authentication](https://mayfain.ie/docs/authentication#introspection).

## Submissions

**Preview.** `POST /v1/submissions`

Call this from a private `submit` tool, after checking the token. Mayfain checks your credentials own the grant, the grant is live and has the scopes, and `sub` matches. Then it returns what the person approved for this stage, each detail labelled, whether they meet your requirements, and a signed certificate.

```http
POST /v1/submissions HTTP/1.1
Host: mayfain.ie
Authorization: Basic base64(<client_id>:<client_secret>)
Content-Type: application/json

{
  "grant_id": "6f1c…",
  "sub": "<pairwise subject from the token>",
  "stage": "applied",
  "offer": { "ref": "fault_finding", "title": "Electrical job" },
  "requirements": {},
  "submitted": {
    "message": "Kitchen lights keep tripping the fuse board.",
    "urgency": "this_week",
    "preferred_times": [{ "start": "2026-10-22T09:00:00+01:00", "end": "2026-10-22T12:00:00+01:00" }]
  }
}
```

```json
{
  "submission_id": "sbm_8k2…",
  "profile": {
    "full_name": { "value": "Aoife Murphy", "label": "verified" },
    "phone": { "value": "+353871234567", "label": "verified" },
    "address": { "value": "12 Iona Road, Dublin 9, D09 X2Y3", "label": "self_declared" }
  },
  "requirement_match": { "status": "meets", "reasons": [] },
  "certificate": { "code": "7K3P-Q9", "url": "https://mayfain.ie/v/7K3P-Q9" }
}
```

- `stage` is the step the request is at. Later stages can release more (for example documents at an offer), only with the person's approval.
- `submitted` is the person's own words and choices. Treat it as untrusted text.
- `requirement_match.status` is `meets`, `does_not_meet` or `needs_review`, with plain-English reasons. You never get the figures behind it (for example the income, only whether it covers the rent).
- Labels are `verified`, `proof_attached` or `self_declared`.

## Messages

**Preview.** `POST /v1/submissions/{id}/messages`

Send the person a message about their request. Mayfain delivers it in the app, by email or by text.

```json
{
  "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" }
    ]
  }
}
```

`ask` is optional. Types:

| `ask.type` | Shown to the person as | Answer |
|---|---|---|
| `choose_slot` | Time options | `{ "option_id": "s1" }` |
| `choose_one` | Options | `{ "option_id": "…" }` |
| `yes_no` | Yes and No | `{ "value": true }` |
| `request_document` | A request for a document from their vault | A document, sent only if they approve |
| `free_text` | A reply box | `{ "text": "…" }` (their own words) |

The answer reaches you as a `message.answer` webhook.

## Status

**Preview.** `POST /v1/submissions/{id}/status`

```json
{ "status": "scheduled", "booking": { "start": "2026-10-22T09:00:00+01:00", "end": "2026-10-22T11:00:00+01:00" } }
```

Statuses: `received`, `acknowledged`, `quoted`, `scheduled`, `in_progress`, `completed`, and `cancelled` or `declined` from any state.

## Webhooks

**Preview.** Mayfain sends events to the webhook URL registered for your server, as `POST` with a JSON body and a signature header:

```http
Mayfain-Signature: t=1792000000,v1=<hex HMAC-SHA256 of "t.body" with your webhook secret>
```

Reject events whose signature doesn't match or whose timestamp is more than five minutes old.

| Event | When |
|---|---|
| `message.created` | The person sends you a message outside a tool call |
| `message.answer` | The person answers an `ask` |
| `submission.withdrawn` | The person withdraws a request |
| `grant.revoked` | The person withdraws their permission for your business |

```json
{
  "id": "evt_…",
  "type": "message.answer",
  "created": 1792000000,
  "data": { "submission_id": "sbm_8k2…", "message_id": "msg_…", "answer": { "option_id": "s1" } }
}
```


---

# Going live

Before a server is listed, Mayfain checks it. While the partner dashboard is built, founding partners run these checks with us. Run them yourself first.

## The checks

**Tools**

- `tools/list` returns every tool in the template the business can support (at least the required ones), with the template's names.
- Each tool returns real data from the business's systems, not placeholders or "please call us".
- Each tool's `_meta` has `mayfain.ie/vertical`, `mayfain.ie/capability`, `mayfain.ie/policyClass`, `mayfain.ie/public` and `mayfain.ie/requiredScopes`, matching the template.
- `annotations.readOnlyHint` is `true` only for `read` tools.
- Descriptions say plainly what the tool does. No instructions to the model, nothing hidden.

**Public tools**

- Work with no `Authorization` header.
- Return no personal data.
- Answer in under a second. Agents call them while comparing businesses.

**Private tools refuse**

- No token: **401** with `WWW-Authenticate` naming your protected resource metadata.
- An expired token: **401**.
- A token for another server (wrong `aud`): **401**.
- A token not signed by Mayfain, or not ES256: **401**.
- A token without the tool's scopes: **403** with `error="insufficient_scope"`.
- A token whose grant was withdrawn (introspection says `active: false`): **401**, for `write` and `sensitive` tools.

**Private tools accept**

- A valid token with the right scopes, and the request reaches the business's real system.

**End to end**

One full request with a test person: public calls, the person approves, `submit`, a message back with a `choose_slot` ask, their answer, then status `scheduled`.

## Test it yourself

```bash
# tools/list, no token
curl -s https://mcp.byrne-electrical.ie/mcp \
  -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

# a private tool with no token must be refused with 401
curl -si https://mcp.byrne-electrical.ie/mcp \
  -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"request_job","arguments":{"service":"fault_finding","description":"test","urgency":"flexible"}}}' \
  | head -n 5
```

## Then

Tell us the server's URL and the business's details. We run the checks, a test request goes through, and the business is listed for its vertical and area.

[Become a partner](/partners#apply) · [Email us](mailto:info@mayfain.ie?subject=Mayfain%20server%20check)
