Skip to content

MCP endpoint

Booking hosts an unauthenticated MCP server for Appointment Booking's link-holder personas. The product behaviour is described under Agent access; the placement decision and the rejected alternatives are in ADR-0012. This page is the wire-level contract and the implementation notes.

Mount point and transport

  • Route directory src/routes/booking/mcp/, picked up by the fastify-sdk autoloader like any other route. No manual registration in src/index.ts. The route is hide: true for Swagger: it is a protocol surface, so it has no place in openapi.yaml.
  • POST /booking/mcp handles the JSON-RPC messages. GET and DELETE return 405 with an allow: POST header.
  • It mounts beside /booking/v1, not under it: MCP is a protocol surface, not a REST version. This keeps ADR-0005's question of who consumes /v1 clean, and matches both org precedents (/api/mcp/ in the ai-service, /mcp in GLAM).
  • The transport is stateless, following the ai-service's precedent (their ADR-0018): each request builds a server from @modelcontextprotocol/sdk, registers the tools, connects a StreamableHTTPServerTransport with sessionIdGenerator: undefined and enableJsonResponse: true, and hands the raw request/response pair over after reply.hijack(). Fastify has already parsed the body, so it is passed in rather than read from the stream. No session table, no replica affinity, no SSE stream.

The module layout under src/mcp/:

FileHolds
server.tsbuildMcpServer(): the tools/list and tools/call handlers, argument validation, and the mapping from failures to tool results and metric outcomes
tools.tsThe catalog: one entry per tool with its schemas, annotations, and handler
capability.tsURL-or-id parsing for the page and manage parameters
format.tsWindow defaults, the response cap, instant formatting, and the end-user-content caps
limits.tsThe per-capability write limiter

Tools call services, not routes

Tool handlers import src/services/* directly rather than calling booking's own HTTP API: slot derivation (loadSlotDerivationInput and deriveSlots in src/services/slots.ts), createBooking, cancelBookingByManageToken, rebookBooking, and the same serializers the routes use (src/services/booking-views.ts), so MCP and REST return identical shapes.

resend_manage_link is the one tool without a REST counterpart: resendManageLinks in src/services/manage-link.ts looks up upcoming bookings by appointment type and booker address (listUpcomingBookingsByEmail) and sends their manage links through the existing outbox (ADR-0011) using the booking-manage-link template, in each booking's stored locale. The service returns how many mails it enqueued for logs and tests only; the tool drops that number, because surfacing it would turn the uniform acknowledgment into an existence oracle.

The booking domain counters already increment in the service layer, so this endpoint needs no metrics refactor. One piece of debt to clear before any poll tool lands: booking_voters_total and booking_votes_total increment in the route handlers (src/routes/booking/v1/polls/_pollId/voters/index.ts and the _voterId sibling), so an in-process tool path would bypass them. Move those increments into the service layer first, so both surfaces count.

Tool catalog

ToolParametersReturns
get_booking_pagepage (URL or appointment-type id)The public page view: title, description, location, duration, owner display name, status. Nothing beyond the public REST whitelist (appointmentTypeToPublicJsonV1).
list_available_slotspage, from/to (optional calendar dates), timezone?/locale? (for labels)Available slots as {start, end} UTC instants with localized labels. Defaults to a 7-day window, caps the slot count per response, and returns a nextFrom continuation date when truncated.
book_slotpage, start (UTC instant from the slot list), name, email, message?, locale?, timezone?Booking confirmation: when (localized), the appointment details, and the manage URL. The text output notes that a confirmation email carries the durable manage link.
get_managed_bookingmanage (manage token or manage URL), timezone?/locale?The booking's status, whether it is still cancellable or rebookable, and the public page data needed to pick a new slot.
cancel_bookingmanage, timezone?/locale?The cancelled booking. destructiveHint: true. Idempotent, as on the REST surface.
rebook_bookingmanage, start, name?, message?, reason?, timezone?/locale?A new confirmation, including the new manage URL: the appointment moves in place (one iMIP UPDATE and one mail per party) and a fresh manage token replaces the old one. name/message follow the page's semantics: omitted keeps the stored value, and an empty message clears the note. reason explains this move to the owner and never overwrites message.
resend_manage_linkpage, emailA uniform acknowledgment. If upcoming bookings exist for that address on this page, their manage links are re-sent to the stored booker address. The response never discloses whether a booking exists.

Slots have no ids. Availability is derived, never stored, so a booking targets a start instant; if the slot is taken between listing and booking, book_slot returns a structured "slot unavailable" error and its description tells the agent to re-list and retry with a fresh instant rather than guessing. The REST slot route accepts up to 31 days; the tool's 7-day default and response cap are independent of that, and exist so a single call cannot flood an agent's context.

There is no verify tool. On a page with Require email verification on, createBooking itself refuses with VERIFICATION_REQUIRED (0x8406) unless the verify route calls it after a code was consumed, so no caller of the service can skip the code. get_booking_page carries emailVerification, and the book_slot description tells the agent to send the booker to the page.

Conventions

These follow the ai-service's house style, so agents already using the App Suite MCP server find the same shape here.

  • Schemas are plain JSON Schema. The SDK's high-level McpServer takes Zod shapes; this service validates every route with JSON Schema through AJV, so the MCP layer uses the low-level Server instead and declares tools in the wire format directly. Arguments are validated with the SDK's own AjvJsonSchemaValidator, compiled once per tool. No second schema DSL enters the codebase, and tools/list returns the schemas verbatim.
  • Bounded input, no ambiguous patterns. Validation runs before any handler or rate limit, so every free-text argument has a maxLength (the REST body limit where one exists), and the email check is the linear isPlausibleEmail from the REST create, run in the handler, not a regex pattern: a backtracking pattern would let one argument stall the event loop.
  • Structured output. Every tool declares an outputSchema and returns structuredContent. The human-readable text part is a short summary and never the only carrier of data. The low-level Server validates the result envelope against CallToolResultSchema, not against the tool's own output schema, so error results may carry structuredContent too.
  • Domain failures are tool results, not protocol errors. A failed booking, an unknown id, or a closed poll returns isError: true with a structured {code, message} payload from the catalog in src/appsuite/errors.ts, so the agent can relay and react. Protocol errors are reserved for malformed requests — including an unknown tool name, which answers -32602 (invalid params) exactly as the spec and the SDK's own McpServer do. Slot-refusal reasons stay opaque ("slot unavailable"), matching the REST contract.
  • Annotations. Tools carry readOnlyHint, destructiveHint, and idempotentHint, so clients can ask their user before destructive calls.
  • Links or ids as input. Every capability parameter accepts either the bare id/token or the full pasted URL. Parsing is strict local string matching against the configured bookingBaseURL (and pollBaseURL, once poll tools exist); the server never fetches a URL, so the parameter is not a request-forgery vector.
  • Times are dual. Instants are ISO-8601 UTC plus a pre-localized human label in the requested, or page-default, timezone.
  • Untrusted content is marked and capped. Tool descriptions name which output fields are end-user content (page title, description, location, identity display name and info, booker name, message, form questions and answers), and those fields are length-capped in tool output. The text summary carries none of them, only duration, status and the server-made time label, so owner-written text never reads as the server's own words.

Note on the error handler: src/plugins/errors.ts branches on a /booking/v1/ URL prefix, so /booking/mcp falls into the legacy {code, error} branch. The MCP layer catches AppError itself and converts it into a tool result, so the HTTP error handler only ever sees transport-level failures on this path.

Configuration

An mcp.enabled flag, default false, in the hot-reloaded flat config (src/config.ts, config/config.yaml). Route registration is not hot-reloadable, so the route registers unconditionally and checks the flag per request, answering 404 while disabled. This preserves the config system's reload property (ADR-0007) and gives operators an off switch that needs no restart.

Rate limiting

Two layers, both required because an MCP endpoint invites scripted traffic:

  • An endpoint-level per-IP limit on POST /booking/mcp covering all calls, including reads. This is the first read-side limit in the service: today only public writes opt into PUBLIC_WRITE_LIMIT (src/plugins/rate-limit.ts), yet slot derivation is the costliest read booking performs, and initialize and tools/list are free compute for anyone. The limit counts HTTP requests, so the route refuses JSON-RPC batches (an array body) with 400 and -32600 before the transport sees them: one request is one message. The stateless tool surface has no use for batching, and the MCP spec dropped it in 2025-06-18.
  • Per-capability-id limits on write tools in src/mcp/limits.ts, because per-IP limits fail in both directions under AI-provider NAT: one provider's egress pool can exhaust a per-IP budget for everyone behind it, and distributed callers evade it. book_slot and rebook_booking share one bucket per appointment type (RATE_LIMIT_MCP_PAGE_MAX, default 20 per minute).
  • resend_manage_link has its own per-page bucket (same RATE_LIMIT_MCP_PAGE_MAX ceiling, so a mail flood cannot eat the page's booking budget) plus a cap per target address (RATE_LIMIT_MCP_RESEND_MAX, default 3 per minute), since each call can send mail.

A refused tool call surfaces as MCP_RATE_LIMITED (0x8200, HTTP status 429 in the catalog though it never reaches an HTTP body). All limits are fixed-window, per-replica in-memory state, the same limitation PUBLIC_WRITE_LIMIT has. A tool charges its buckets only after the page has been found, so an unknown id gets the plain not-found and leaves nothing behind. The address bucket is keyed by a hash of the lowercased address, so its size does not depend on the input. Buckets are evicted as soon as their window has passed.

Logging

Tool parameters carry manage tokens, so nothing on this path logs them: the route logs no body, and the MCP layer logs the tool name and the error on an unexpected failure, never the arguments. Keep it that way. Adding an argument dump for debugging would put live capabilities into the service's own logs, which is exactly what the threat model promises it does not do.

Metrics

One new counter, booking_mcp_tool_calls_total{tool, outcome} with outcomes ok | domain_error | invalid | not_found, defined in src/services/metrics.ts alongside the existing booking_* counters. The tool label only ever carries catalog names plus the literal unknown (for calls to a name outside the catalog): caller-controlled strings must never become label values, or a sweep could mint unbounded time series. The domain counters keep firing from the services, so booking totals stay comparable across surfaces. The not_found outcome doubles as the enumeration-sweep signal (see Monitoring).

Deployment

No new workload. The endpoint shares the existing pod and port, and the existing /booking routing covers /booking/mcp. Changes are values-level only: the mcp block in the config ConfigMap and the rate-limit knobs. Stateless transport means no session affinity and no long-lived-connection timeout concerns.

Tests

  • test/mcp/ covers the pure parts: capability parsing (including links pointing at another host, which must be rejected rather than followed), the window and truncation maths, and the limiter's window behaviour.
  • test/routes/mcp_test.ts drives real JSON-RPC over app.inject: the disabled-flag 404, the 405s, initialize without a session id, tool discovery, and the tool-result shape of an unknown page or a bad argument. The two repositories the read tools touch are mocked.
  • integration/mcp_test.ts runs the DB-backed tool paths against MariaDB: booking, the slot-taken refusal, cancel idempotence, rebook invalidating the old manage link, truncation and resumption over a wide window, and the manage-link recovery guarantees (mail to the stored address, identical answer for an address with no bookings, nothing for a cancelled booking).

Test caveat, shared with the other API suites: autoload imports route files outside vitest's module graph, so an autoloaded route gets its own copy of src/config.ts and would never see applyServiceConfig() from a test. Both MCP suites therefore register the route module directly on a bare Fastify instance, which is what makes mcp.enabled and bookingBaseURL testable.

Driving it from a real client

The endpoint is an ordinary remote MCP server, so any client that speaks Streamable HTTP can drive it with no credential. MR previews enable mcp.enabled (.gitlab/argocd/values/booking-preview.yaml), which makes a preview host the easiest target:

# Claude Code, scoped to this checkout
claude mcp add --scope local --transport http booking-preview \
  https://<preview-host>/booking/mcp

# MCP Inspector, transport "Streamable HTTP", same URL
npx @modelcontextprotocol/inspector

A raw call needs both media types in Accept, which is what the transport enforces:

curl -X POST https://<preview-host>/booking/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

The tools need a booking page to point at: create one in the App Suite UI on the target host and give the client its link. Mail lands in the preview's mailpit sink at /mailpit/, where the manage link a tool result mentions can be read back. A preview runs two replicas, so the per-capability limits above allow roughly twice their configured ceiling before 0x8200 appears.