promptunit

WebMCP Action Planner: Let AI Agents Use Your Site Safely

Soon AI agents won't just read your site. They will book, search, add to cart and fill forms for people. This prompt plans which actions to offer AI agents through WebMCP, drafts the tool definitions and builds in safety rules from day one.

Works in ChatGPTClaudeGemini609 words6 inputs to fillSEO-019

Example input

This is exactly what we gave the model. You replace it with your own details.

- Website: https://www.example.com (bike repair and rental shop with two locations)
- Site type: Booking site with a small online shop
- Main things users do on the site: Check repair prices, book a repair slot, rent a bike for a day, check opening hours, track a repair, buy spare parts
- Actions that need login or payment: Booking a repair (needs a deposit), renting a bike (needs payment and ID), tracking a repair (needs a booking code)
- Tech stack: Next.js with a custom booking API and Stripe
- Platform or CDN features available: Cloudflare (free plan)

Real output

Pasted straight from the model. We did not fix a word.

WebMCP plan for example.com (bike repair and rental, two shops)

Before you build: WebMCP is experimental and the API is still changing. Check the latest WebMCP draft spec from the W3C community group and the current Chrome and Edge docs before you write production code. All code in this plan is a draft.

What this will and won't do for you: WebMCP lets an AI agent in a customer's browser check your prices, free slots, rental bikes and repair status directly, instead of clicking around your pages. It does not change your Google rankings or AI citations. Safari (WebKit opposes it) and Firefox (Mozilla is neutral) users won't get it, so treat it as an extra layer on top of your normal site, never a replacement for it.

Quick questions (I've used my best guess for each)

  1. Do customers have accounts, or do they book as guests? Guess: guests only. They book with name, email and phone, and get a booking code by email.
  2. What do your repair booking codes look like? Guess: short codes like K7QM-82XD. That is too short to be safe on its own, so I pair the code with the last 4 digits of the customer's phone number.
  3. How do you check ID for rentals? Guess: the customer shows photo ID in the shop at pickup. The website takes payment only.
  4. How are the two shops set up? Guess: each shop has its own repair slots and rental bikes. Spare parts are sold online, with stock shown per shop.
  5. Where is Next.js hosted, and does traffic go through Cloudflare? Guess: Vercel or a Node server, with DNS proxied through Cloudflare (orange cloud). Your booking API already has JSON endpoints for prices, slots and repair status.

The location IDs (shop_a, shop_b), service lists, bike types, currency (EUR) and all prices, times and codes in the examples are placeholders or guesses. Replace them with your real values.


1. Action table

ActionUser valueRiskLogin neededPhase
Get opening hours and shop details (get_shop_info)High. Common question, includes holiday closures for both shopsRead-onlyNo1
Get repair prices (get_repair_prices)High. "How much for a puncture on an e-bike?" answered exactlyRead-onlyNo1
Check free repair slots (check_repair_slots)High. Agent can compare both shops and find the soonest slotRead-only (no hold)No1
Check rental bikes and day price (check_rental_availability)High. "Is there a medium e-bike free Saturday?"Read-only (no reservation)No1
Search spare parts with price and stock (search_spare_parts)Medium. Helps buyers find the right tube or brake padsRead-onlyNo1
Track a repair (track_repair)High for existing customers. Cuts "is my bike ready?" callsRead-only, but shows personal booking dataBooking code + last 4 phone digits2
Add a part to cart (add_part_to_cart)Medium. Saves clicks; customer still checks out aloneChanges data (cart only, no payment)No3
Prepare a repair booking (prepare_repair_booking)High. Agent fills in the booking and the customer confirmsChanges data + spends money (deposit)No account; contact details + deposit paid by the customer3
Prepare a bike rental (prepare_bike_rental)Medium–highChanges data + spends money + ID checkPayment by the customer; ID shown at pickup4
Reschedule a repair bookingMediumChanges data (may affect deposit)Booking code + phone digits4 (only if Phase 3 runs clean)
Pay, enter card details, upload ID, cancel or refund, change contact details, approve extra repair costs, apply discount codesn/aSpends money / changes account datan/aNever offered as tools

2. Tool definitions (first set: Phases 1–2, plus a Phase 3 preview)

Rules for every tool:

  • additionalProperties: false everywhere.
  • The server checks every input again. The schema in the browser is only a hint.
  • Outputs contain only listed fields, and never contain free text written by customers or suppliers.

2.1 get_shop_info (Phase 1)

Description: "Get address, phone and opening hours for one or both shops, including holiday closures, for up to 14 days. Read-only."

{
  "type": "object",
  "properties": {
    "location_id": {
      "type": "string",
      "enum": ["shop_a", "shop_b", "all"],
      "default": "all",
      "description": "Which shop. 'all' returns both."
    },
    "from_date": {
      "type": "string",
      "format": "date",
      "description": "First day, YYYY-MM-DD. Default: today. Max 60 days ahead."
    },
    "days": { "type": "integer", "minimum": 1, "maximum": 14, "default": 7 }
  },
  "additionalProperties": false
}

Example output

{
  "timezone": "Europe/Berlin",
  "locations": [
    {
      "location_id": "shop_a",
      "name": "Shop A",
      "address": "12 Sample Road",
      "phone": "+00 0000 0000",
      "hours": [
        { "date": "2026-12-04", "open": "09:00", "close": "18:00" },
        { "date": "2026-12-06", "closed": true, "note": "Closed on Sundays" }
      ],
      "page_url": "https://www.example.com/locations/shop-a"
    }
  ]
}

2.2 get_repair_prices (Phase 1)

Description: "Get current bike repair prices. Filter by service or bike type. Prices are starting prices; the final price is confirmed after inspection. Read-only."

{
  "type": "object",
  "properties": {
    "service": {
      "type": "string",
      "enum": ["puncture", "basic_service", "full_service", "brakes", "gears", "wheel_truing", "ebike_check", "other"],
      "description": "Type of repair. Leave out to list all."
    },
    "bike_type": {
      "type": "string",
      "enum": ["city", "road", "mountain", "hybrid", "ebike", "kids", "cargo"]
    }
  },
  "additionalProperties": false
}

Example output

{
  "currency": "EUR",
  "updated_at": "2026-11-28",
  "prices": [
    {
      "service": "puncture",
      "bike_type": "ebike",
      "name": "Puncture repair, e-bike",
      "price_from": 25.0,
      "parts_included": false,
      "typical_turnaround_days": 1,
      "deposit": 10.0
    }
  ],
  "note": "Starting prices. Final price is confirmed after inspection."
}

2.3 check_repair_slots (Phase 1)

Description: "List free drop-off slots for a repair at one shop for up to 14 days. Does not book or hold a slot. Read-only."

{
  "type": "object",
  "properties": {
    "location_id": { "type": "string", "enum": ["shop_a", "shop_b"] },
    "service": {
      "type": "string",
      "enum": ["puncture", "basic_service", "full_service", "brakes", "gears", "wheel_truing", "ebike_check", "other"]
    },
    "bike_type": {
      "type": "string",
      "enum": ["city", "road", "mountain", "hybrid", "ebike", "kids", "cargo"]
    },
    "from_date": {
      "type": "string",
      "format": "date",
      "description": "YYYY-MM-DD, today up to 60 days ahead."
    },
    "days": { "type": "integer", "minimum": 1, "maximum": 14, "default": 7 }
  },
  "required": ["location_id", "service"],
  "additionalProperties": false
}

Example output

{
  "location_id": "shop_b",
  "service": "full_service",
  "currency": "EUR",
  "deposit": 20.0,
  "slots": [
    {
      "slot_id": "s_9f3k2q7xm4",
      "drop_off_start": "2026-12-03T08:30:00+01:00",
      "drop_off_end": "2026-12-03T10:00:00+01:00",
      "ready_estimate": "2026-12-04"
    }
  ],
  "booking_page_url": "https://www.example.com/book?location=shop_b&service=full_service"
}

2.4 check_rental_availability (Phase 1)

Description: "Check which rental bikes are free at one shop on one day, with day price and deposit. Does not reserve a bike. Read-only."

{
  "type": "object",
  "properties": {
    "location_id": { "type": "string", "enum": ["shop_a", "shop_b"] },
    "date": {
      "type": "string",
      "format": "date",
      "description": "Rental day, YYYY-MM-DD, today up to 60 days ahead."
    },
    "bike_type": {
      "type": "string",
      "enum": ["city", "road", "mountain", "ebike", "kids", "cargo"]
    },
    "rider_height_cm": {
      "type": "integer",
      "minimum": 90,
      "maximum": 210,
      "description": "Optional. Used only to suggest a frame size."
    }
  },
  "required": ["location_id", "date"],
  "additionalProperties": false
}

Example output

{
  "location_id": "shop_a",
  "date": "2026-12-05",
  "currency": "EUR",
  "pickup_window": "09:00-11:00",
  "return_by": "18:00",
  "bikes": [
    {
      "bike_type": "ebike",
      "model": "Sample E-City 500",
      "size": "M",
      "fits_height_cm": "165-180",
      "available": 3,
      "price_per_day": 45.0,
      "deposit": 200.0
    }
  ],
  "payment": "online, by the customer",
  "id_required": "photo ID shown at pickup"
}

2.5 search_spare_parts (Phase 1)

Description: "Search spare parts in the online shop by keyword, category or wheel size. Returns price and stock per shop. Does not add to cart. Read-only."

{
  "type": "object",
  "properties": {
    "query": {
      "type": "string",
      "minLength": 2,
      "maxLength": 60,
      "description": "Keywords, e.g. '700x28 inner tube' or 'disc brake pads'."
    },
    "category": {
      "type": "string",
      "enum": ["tubes", "tyres", "brake_pads", "chains", "cassettes", "cables", "lights", "locks", "other"]
    },
    "wheel_size": {
      "type": "string",
      "enum": ["700c", "29", "27.5", "26", "24", "20", "16"]
    },
    "in_stock_only": { "type": "boolean", "default": true },
    "max_results": { "type": "integer", "minimum": 1, "maximum": 20, "default": 10 }
  },
  "required": ["query"],
  "additionalProperties": false
}

Example output

{
  "currency": "EUR",
  "total_matches": 4,
  "results": [
    {
      "sku": "TUBE-700-28-PV",
      "name": "Inner tube 700x25-32c, Presta 48 mm",
      "price": 7.5,
      "stock": { "shop_a": 14, "shop_b": 0, "online": 22 },
      "product_url": "https://www.example.com/shop/tube-700-28-pv"
    }
  ]
}

2.6 track_repair (Phase 2)

Description: "Get the status of an existing repair. Needs the booking code from the confirmation email and the last 4 digits of the phone number on the booking. Returns repair status only, no personal details. Read-only."

{
  "type": "object",
  "properties": {
    "booking_code": {
      "type": "string",
      "pattern": "^[A-Z0-9]{4}-[A-Z0-9]{4}$",
      "description": "Code from the booking confirmation email, e.g. K7QM-82XD."
    },
    "phone_last4": {
      "type": "string",
      "pattern": "^[0-9]{4}$",
      "description": "Last 4 digits of the phone number used for the booking."
    }
  },
  "required": ["booking_code", "phone_last4"],
  "additionalProperties": false
}

(The code pattern is a guess. Match it to your real format.)

Example output (found)

{
  "found": true,
  "status": "waiting_for_parts",
  "status_label": "Waiting for parts",
  "location_id": "shop_a",
  "ready_estimate": "2026-12-06",
  "quote_total": 85.0,
  "deposit_paid": 20.0,
  "balance_due_at_pickup": 65.0,
  "currency": "EUR",
  "customer_action_needed": "none"
}

Example output (not found, or wrong digits: same answer for both)

{ "found": false, "message": "No repair matches this code and phone number." }
  • status enum: received, waiting_for_parts, in_progress, ready_for_pickup, collected.
  • customer_action_needed enum: none, approve_extra_cost_via_email_link, collect_bike. The agent can never approve extra costs.

2.7 Preview: prepare_repair_booking (Phase 3, not in the first set)

This shows how a money-related tool must work. It holds a slot and asks the human. It never books or charges.

Description: "Prepare a repair booking for the customer to confirm. Holds the chosen slot for 10 minutes and shows a summary on the page. Does not book and does not take payment. The customer must confirm and pay the deposit themselves."

{
  "type": "object",
  "properties": {
    "slot_id": {
      "type": "string",
      "pattern": "^s_[a-z0-9]{8,32}$",
      "description": "A slot_id returned by check_repair_slots."
    },
    "service": {
      "type": "string",
      "enum": ["puncture", "basic_service", "full_service", "brakes", "gears", "wheel_truing", "ebike_check", "other"]
    },
    "bike_type": {
      "type": "string",
      "enum": ["city", "road", "mountain", "hybrid", "ebike", "kids", "cargo"]
    },
    "problem_summary": {
      "type": "string",
      "maxLength": 300,
      "description": "Short plain-text description of the problem."
    },
    "contact_prefill": {
      "type": "object",
      "description": "Optional. Only pre-fills the form. The customer checks it before confirming.",
      "properties": {
        "name": { "type": "string", "maxLength": 80 },
        "email": { "type": "string", "format": "email", "maxLength": 120 },
        "phone": { "type": "string", "pattern": "^\\+?[0-9 ]{7,20}$" }
      },
      "additionalProperties": false
    }
  },
  "required": ["slot_id", "service", "bike_type"],
  "additionalProperties": false
}

Example output

{
  "status": "awaiting_customer_confirmation",
  "hold_expires_at": "2026-12-01T14:40:00+01:00",
  "summary": {
    "location_id": "shop_b",
    "drop_off": "2026-12-03 08:30-10:00",
    "service": "Full service",
    "price_from": 89.0,
    "deposit": 20.0,
    "currency": "EUR",
    "cancellation": "Free cancellation until 24 h before drop-off"
  },
  "message": "Shown to the customer on the page. Nothing is booked and no money is taken until the customer confirms and pays the deposit."
}

Later results the tool can return: awaiting_payment_by_customer, cancelled_by_customer, hold_expired, slot_taken.


3. Safety rules checklist

Money and confirmation

  • No tool takes payment, sees card details or creates a paid booking or rental. The customer pays only in Stripe (Checkout or the embedded Payment Element).
  • A repair booking or rental exists only after your Stripe webhook confirms payment (checkout.session.completed or payment_intent.succeeded). Check the webhook signature.
  • Any tool that holds a slot, fills a booking or changes a cart shows a clear summary on the page first: shop, date and time, service, price, deposit and cancellation rules. Then it waits for the customer's own click. Use the browser's user-interaction step (requestUserInteraction in current drafts; check the spec) where it is supported.
  • Slot holds expire after 10 minutes. Allow 1 active hold per browser session and about 3 per IP per hour (a starting guess). This stops a manipulated agent from blocking your repair calendar.
  • There are no tools for paying, uploading ID, cancelling, refunds, changing contact details, approving extra repair costs or discount codes.
  • Rental ID checks stay outside WebMCP: ID is shown at pickup (guess), or uploaded by the customer in a normal form.

Input validation (server)

  • Every /api/agent/* route checks the input again with zod (or similar), using the same rules as the JSON Schema. It rejects unknown fields (.strict()).
  • Use enums for shop, service and bike type. Dates must be from today up to 60 days ahead. Set length limits on all text.
  • slot_id and hold_id are random and unguessable, and are checked against live availability on every call.
  • Free text (problem_summary, search query) is stored and shown as plain text only, and escaped in your staff screens.

Rate limits (Cloudflare free plan + app)

  • Put every agent endpoint under /api/agent/. Then one Cloudflare rate-limiting rule covers them all. The free plan includes only a small number of basic rules, so check what your dashboard allows. Start around 20 requests per 10 seconds per IP and tune from your logs.
  • Add per-tool limits in the app. track_repair: 5 attempts per booking code per hour and 5 per IP per minute. Use a shared store such as Redis; in-memory counters don't work on serverless.
  • Kill switch: a server env flag, plus a Cloudflare WAF custom rule that blocks /api/agent/*, built ahead of time and left switched off.
  • Test that Cloudflare bot settings (for example Bot Fight Mode) don't block real customer sessions that use an agent.

Responses and secrets

  • Allowlist every output field. Never pass raw booking-API or Stripe objects through.
  • Never return any of these: API keys, Stripe client secrets or IDs, staff notes, staff names, or customer name, email, phone or address.
  • Never return text that someone else wrote (customer notes, reviews, supplier descriptions). It can carry hidden instructions to the agent (prompt injection).
  • Give the same answer for "unknown booking code" and "wrong phone digits".
  • Booking codes are random, with at least 8 characters, and are always paired with the phone-digit check.
  • Errors are short codes like { "error": "slot_taken" }, with no stack traces.
  • Hours, prices and parts can be cached for a few minutes. Slots, rentals and repair status must be live (no-store).

Descriptions

  • Keep descriptions short and factual. Each one says what the tool does not do ("Does not book", "Does not take payment").
  • No marketing text, and no instructions to the agent beyond how to use the tool.
  • Any change to a tool name, description or schema goes through code review like any other code change.
  • Check whether Cloudflare or any third-party script (chat widget, analytics, plugins) adds default tools to your pages. Turn them off or edit their descriptions, and avoid name clashes. Any script on your page can register tools, so keep third-party scripts few and use a Content Security Policy.

Logging

  • Log every agent call: time, tool, result code, latency, session ID, hashed IP, country (CF-IPCountry) and user agent.
  • Redact inputs: hash booking codes, and never log phone digits or contact details.
  • Alert on spikes in errors, failed track_repair lookups, rate-limit hits or slot holds.
  • Keep logs 30–90 days. Mention agent access in your privacy policy, because data returned to an agent goes to the customer's AI provider.

4. Rollout plan with phases

Phase 0: Prepare (about 1 week)

  • Read the latest WebMCP draft spec and the Chrome and Edge docs. Note the current API shape and how to join an origin trial (tokens are per origin and they expire).
  • Check your live pages for tools that are already registered by Cloudflare or third-party scripts.
  • Build the /api/agent/* routes with zod checks, field allowlists, logging and the kill switch.
  • Set up the Cloudflare rate-limit rule and prepare the WAF block rule (off).
  • Check that your booking codes are long enough and random.

Phase 1: Read-only prototype behind a flag (weeks 2–4)

  • Tools: get_shop_info, get_repair_prices, check_repair_slots, check_rental_availability, search_spare_parts.
  • Turn the flag on in a preview deployment first, then for staff only.
  • Test in Chrome and Edge (flag or origin trial) and in Brave (experimental). Confirm that Safari and Firefox see the normal site with no errors.
  • Run about 20 real customer questions through an agent and compare the answers with your real data. For example:
    • "Is Shop B open on Boxing Day?"
    • "Cheapest full service for a hybrid this week, at either shop?"
    • "Medium e-bike free Saturday?"
  • Injection test on staging: add a test part whose name contains an instruction to the agent. Check how the agent handles it. Then tighten which text you return.
  • Go to Phase 1b if: error rate is under 2%, answers match your site, and no personal data shows up in responses or logs.

Phase 1b: Public read-only (weeks 4–6)

  • Turn the flag on for everyone, with an origin trial token if needed.
  • Measure:
    • calls per tool per day
    • success and error rate
    • validation rejections
    • p95 latency
    • rate-limit hits
    • how many agent sessions lead to a customer starting a booking or checkout in the normal UI
    • support complaints like "the AI told me the wrong price"

Phase 2: track_repair (from week 6)

  • Staff test it with real booking codes first, then release it.
  • Watch the ratio of failed to successful lookups and any patterns of guessing.
  • Go to Phase 3 if: no enumeration attempts get through, and support calls about repair status go down.

Phase 3: First actions with confirmation (after 4–6 clean weeks)

  • Tools: add_part_to_cart and prepare_repair_booking.
  • Staff first, then a small share of visitors behind the flag.
  • Measure:
    • holds created vs confirmed vs expired
    • deposits paid
    • bookings without payment (must be 0)
    • no-shows from agent-prepared bookings
  • Go to Phase 4 if: there are zero bookings or charges without a customer click, there are no disputes, and the hold-expiry rate is reasonable.

Phase 4: Rentals and rescheduling

  • prepare_bike_rental: the customer confirms and pays, and ID stays manual.
  • Rescheduling only if Phase 3 stayed clean.
  • Cancelling, refunds and account changes stay human-only.

Ongoing

  • Check the spec and browser docs at least monthly and update the code when the API changes.
  • Renew origin trial tokens before they expire.
  • Review tool descriptions and logs every quarter.

5. Draft code (Next.js App Router + custom booking API + Stripe)

/* =====================================================================
 * DRAFT CODE - NOT PRODUCTION READY
 * WebMCP is experimental. The API shape (navigator.modelContext,
 * registerTool / unregisterTool, the execute() return format,
 * requestUserInteraction, annotations) has changed between drafts
 * and may change again. Check the latest WebMCP draft spec and the
 * Chrome/Edge docs before you build.
 * ===================================================================== */


// ===== lib/agent/tool-defs.ts =====
// One source of truth for tool names, descriptions and JSON Schemas.
// Used by the browser (WebMCP) and mirrored by zod on the server.
export const LOCATIONS = ['shop_a', 'shop_b'] as const;           // placeholder IDs
export const SERVICES = ['puncture', 'basic_service', 'full_service', 'brakes',
  'gears', 'wheel_truing', 'ebike_check', 'other'] as const;      // guess - use your list
export const BIKE_TYPES = ['city', 'road', 'mountain', 'hybrid', 'ebike', 'kids', 'cargo'] as const;

export const TOOL_DEFS: Record<string, { description: string; inputSchema: object }> = {
  get_repair_prices: {
    description:
      'Get current bike repair prices. Filter by service or bike type. ' +
      'Prices are starting prices; the final price is confirmed after inspection. Read-only.',
    inputSchema: {
      type: 'object',
      properties: {
        service: { type: 'string', enum: SERVICES },
        bike_type: { type: 'string', enum: BIKE_TYPES },
      },
      additionalProperties: false,
    },
  },
  // get_shop_info, check_repair_slots, check_rental_availability,
  // search_spare_parts, track_repair, prepare_repair_booking:
  // copy the descriptions and schemas from section 2 of this plan.
};


// ===== components/WebMcpTools.tsx =====
'use client';
import { useEffect } from 'react';
import { TOOL_DEFS } from '@/lib/agent/tool-defs';
import { openBookingConfirmDialog } from '@/components/BookingConfirmDialog'; // your modal, resolves true/false

// Feature flags: OFF by default. Turn on in preview first.
const ENABLED = process.env.NEXT_PUBLIC_WEBMCP === 'on';
const PHASE = Number(process.env.NEXT_PUBLIC_WEBMCP_PHASE ?? '1');

// Which read-only tool goes live in which phase.
const READ_ONLY_TOOLS: Record<string, number> = {
  get_shop_info: 1,
  get_repair_prices: 1,
  check_repair_slots: 1,
  check_rental_availability: 1,
  search_spare_parts: 1,
  track_repair: 2,
};

type ToolResult = { content: { type: 'text'; text: string }[] };
// Check the spec: the expected return format may differ in the current draft.
const asResult = (data: unknown): ToolResult => ({
  content: [{ type: 'text', text: JSON.stringify(data) }],
});

// Every tool calls our own server. Validation, limits and logging live there,
// so a manipulated agent can't skip them. One URL prefix = one Cloudflare rule.
async function callServer(tool: string, input: unknown) {
  const res = await fetch(`/api/agent/${tool}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Agent-Tool': tool }, // label for logs only, not security
    body: JSON.stringify(input ?? {}),
  });
  return res.json().catch(() => ({ error: 'bad_response' }));
}

// Phase 3 only. It HOLDS a slot, the HUMAN confirms on the page, and Stripe takes the money.
const prepareRepairBookingTool = {
  name: 'prepare_repair_booking',
  description: TOOL_DEFS.prepare_repair_booking?.description,
  inputSchema: TOOL_DEFS.prepare_repair_booking?.inputSchema,
  execute: async (input: unknown, client?: any) => {
    const hold = await callServer('prepare_repair_booking', input); // 10-minute hold, NOT a booking
    if (hold.error) return asResult(hold);

    // Show the summary (shop, time, price, deposit, cancellation) and wait for the customer's click.
    const ask = () => openBookingConfirmDialog(hold.summary, hold.hold_id);
    const confirmed: boolean = client?.requestUserInteraction // check spec: name/shape may change
      ? await client.requestUserInteraction(ask)
      : await ask();

    if (!confirmed) {
      await callServer('release_hold', { hold_id: hold.hold_id }); // internal route, NOT registered as a tool
      return asResult({ status: 'cancelled_by_customer' });
    }
    // After the click, the dialog shows Stripe's embedded Payment Element.
    // The customer enters or approves the card. The booking is created ONLY by the
    // Stripe webhook after payment succeeds - never by this tool.
    return asResult({ status: 'awaiting_payment_by_customer', hold_expires_at: hold.expires_at });
  },
};

// Mount once in app/layout.tsx: <WebMcpTools />
// Tools belong to the current tab. Mounting in the layout keeps them during client-side navigation.
export function WebMcpTools() {
  useEffect(() => {
    const mc = (navigator as any).modelContext;
    if (!ENABLED || !mc?.registerTool) return; // unsupported browser: do nothing, the normal site still works

    const tools: any[] = Object.entries(READ_ONLY_TOOLS)
      .filter(([name, phase]) => phase <= PHASE && TOOL_DEFS[name])
      .map(([name]) => ({
        name,
        description: TOOL_DEFS[name].description,
        inputSchema: TOOL_DEFS[name].inputSchema,
        annotations: { readOnlyHint: true }, // check spec: hint name may change
        execute: async (input: unknown) => asResult(await callServer(name, input)),
      }));

    if (PHASE >= 3 && TOOL_DEFS.prepare_repair_booking) tools.push(prepareRepairBookingTool);

    const registered: { name: string; handle: any }[] = [];
    for (const t of tools) {
      try {
        registered.push({ name: t.name, handle: mc.registerTool(t) });
      } catch (err) {
        // For example, a duplicate name (React Strict Mode double-mount in dev,
        // or a third-party script using the same name).
        console.warn('[webmcp] could not register', t.name, err);
      }
    }

    return () => {
      for (const { name, handle } of registered) {
        // Check spec: some drafts return a handle with unregister(), others use unregisterTool(name).
        if (handle?.unregister) handle.unregister();
        else mc.unregisterTool?.(name);
      }
    };
  }, []);
  return null;
}


// ===== app/api/agent/[tool]/route.ts =====
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createHash } from 'crypto';
import { LOCATIONS, SERVICES, BIKE_TYPES } from '@/lib/agent/tool-defs';
import { bookingApi } from '@/lib/booking-api'; // server-only client for your custom booking API
import { rateLimit } from '@/lib/rate-limit';   // shared store (e.g. Redis); returns true if allowed
import { logAgentCall, redact } from '@/lib/agent-log';

const hash = (s: string) =>
  createHash('sha256').update(s + (process.env.LOG_SALT ?? '')).digest('hex').slice(0, 16);

// Dates: YYYY-MM-DD, from today up to 60 days ahead.
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((d) => {
  const days = (Date.parse(d) - Date.now()) / 86_400_000;
  return days >= -1 && days <= 60;
}, 'date_out_of_range');

type Handler = { schema: z.ZodTypeAny; perIpPerMin: number; run: (input: any) => Promise<unknown> };

const handlers: Record<string, Handler> = {
  get_repair_prices: {
    schema: z.object({
      service: z.enum(SERVICES).optional(),
      bike_type: z.enum(BIKE_TYPES).optional(),
    }).strict(),
    perIpPerMin: 30,
    run: async (input) => {
      const rows = await bookingApi.getPriceList(input);
      // Allowlist output fields. Never pass raw API objects through.
      return {
        currency: 'EUR', // guess
        prices: rows.map((r: any) => ({
          service: r.service,
          bike_type: r.bikeType,
          name: r.publicName, // written by your staff, not by customers
          price_from: r.priceFrom,
          typical_turnaround_days: r.turnaroundDays,
          deposit: r.deposit,
        })),
        note: 'Starting prices. Final price is confirmed after inspection.',
      };
    },
  },

  check_repair_slots: {
    schema: z.object({
      location_id: z.enum(LOCATIONS),
      service: z.enum(SERVICES),
      bike_type: z.enum(BIKE_TYPES).optional(),
      from_date: isoDate.optional(),
      days: z.number().int().min(1).max(14).default(7),
    }).strict(),
    perIpPerMin: 20,
    run: async (input) => {
      const slots = await bookingApi.getFreeSlots(input); // live data, never cached
      return {
        location_id: input.location_id,
        service: input.service,
        slots: slots.map((s: any) => ({
          slot_id: s.publicId, // random public ID, not your database ID
          drop_off_start: s.start,
          drop_off_end: s.end,
          ready_estimate: s.readyEstimate,
        })),
      };
    },
  },

  track_repair: {
    schema: z.object({
      booking_code: z.string().regex(/^[A-Z0-9]{4}-[A-Z0-9]{4}$/), // match your real format
      phone_last4: z.string().regex(/^\d{4}$/),
    }).strict(),
    perIpPerMin: 5,
    run: async ({ booking_code, phone_last4 }) => {
      // Extra limit per booking code, to stop guessing.
      if (!(await rateLimit(`track:${hash(booking_code)}`, { max: 5, windowSec: 3600 }))) {
        return { error: 'too_many_attempts' };
      }
      const r = await bookingApi.getRepairByCode(booking_code);
      // Same answer for "unknown code" and "wrong digits".
      if (!r || r.phoneLast4 !== phone_last4) {
        return { found: false, message: 'No repair matches this code and phone number.' };
      }
      return {
        found: true,
        status: r.status, // enum only - never staff notes
        location_id: r.locationId,
        ready_estimate: r.readyEstimate,
        quote_total: r.quoteTotal,
        deposit_paid: r.depositPaid,
        balance_due_at_pickup: r.balanceDue,
        currency: 'EUR',
        customer_action_needed: r.needsQuoteApproval ? 'approve_extra_cost_via_email_link' : 'none',
        // NOT returned: name, phone, email, address, staff notes, Stripe IDs.
      };
    },
  },

  // get_shop_info, check_rental_availability, search_spare_parts: same pattern.
  // prepare_repair_booking / release_hold: add only when WEBMCP_PHASE >= 3.
  // They create and release short holds, never bookings or charges.
};

export async function POST(req: NextRequest, ctx: { params: Promise<{ tool: string }> }) {
  const { tool } = await ctx.params; // Next.js 15+: params is a Promise
  const started = Date.now();
  const ip = req.headers.get('cf-connecting-ip') ?? 'unknown'; // set by Cloudflare when proxied

  const respond = async (body: any, status: number, input?: unknown) => {
    await logAgentCall({
      tool,
      status,
      ms: Date.now() - started,
      ip_hash: hash(ip),
      country: req.headers.get('cf-ipcountry'),
      ua: req.headers.get('user-agent')?.slice(0, 200),
      input: redact(tool, input), // hash booking codes; drop phone digits and contact details
      error: body?.error ?? null,
    });
    return NextResponse.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
  };

  // Kill switch: turn off every agent tool without a redeploy of the client.
  if (process.env.WEBMCP_SERVER !== 'on') return respond({ error: 'agent_tools_disabled' }, 503);

  const h = handlers[tool];
  if (!h) return respond({ error: 'unknown_tool' }, 404);

  // App-level limit (Cloudflare's rule on /api/agent/* is the first layer).
  if (!(await rateLimit(`ip:${hash(ip)}:${tool}`, { max: h.perIpPerMin, windowSec: 60 }))) {
    return respond({ error: 'rate_limited' }, 429);
  }

  // Never trust the browser-side schema: validate again here.
  const parsed = h.schema.safeParse(await req.json().catch(() => null));
  if (!parsed.success) {
    return respond({ error: 'invalid_input', fields: parsed.error.issues.map((i) => i.path.join('.')) }, 400);
  }

  try {
    return respond(await h.run(parsed.data), 200, parsed.data);
  } catch {
    return respond({ error: 'temporarily_unavailable' }, 502, parsed.data); // no stack traces to agents
  }
}

Next steps:

  1. Correct any of my five guesses that are wrong, especially the booking code format and how you check rental ID.
  2. Check the latest WebMCP draft spec and the Chrome and Edge docs.
  3. Start Phase 0.

The prompt

First lines open so you can see how it is built. The rest opens after purchase.

the prompt · 609 words7 sections
#ROLE
You are a web product architect who understands AI agents, WebMCP and web security. Help me plan which actions my website should offer to AI agents through WebMCP, and how to do it safely.

#INPUTS
Fill in every line. Leave a line blank if you don't know it.
- Website: [WEBSITE URL]
- Site type: [e.g., ecommerce, booking, SaaS app, marketplace, support portal]
- Main things users do on the site: [e.g., search products, check stock, book a slot, track an order, ask for a quote]
Full prompt opens after purchase
Sections inside: #ROLE #INPUTS #FACTS #PROCESS #OUTPUT FORMAT #RULES #QUALITY CHECK

How to use it

  1. Buy, then open it in your account.
  2. Copy the prompt into ChatGPT, Claude or Gemini.
  3. Replace the 6 inputs with your product.
  4. Run it. Use the output. Re-run with a different tone if you like.

Pro tips

  • Start with read-only actions like prices and opening hours. They're safe and show you how agents use your site.
  • Never let an agent pay or book without a clear confirmation from the customer.
  • WebMCP is still experimental. Check the latest draft before your developer builds, because names can change.

Before you buy

Will it work for my product?
Yes, if you can fill the 6 inputs. If the output is bad with your inputs, email us: we fix the prompt and refund you.
Do I download a file?
No. It lives in your account with a copy button, and updates when we improve it.
Which model is best?
Best on Claude. Works in ChatGPT, Claude and Gemini.

Works well with this

Prompts people use in the same campaign.

More in AI Search & Bots

See all in this sub-category

Buying more than two? Lifetime is cheaper.

Every prompt, every category, forever. $59 once. Nothing to download, nothing to renew.

Get lifetime · $59

This prompt

$3$7

  • ✓ Instant access in your account, with a copy button
  • ✓ Example input and real output included
  • ✓ 7-day money-back, no form

Or get every prompt, forever

Lifetime Access · $59 $149 — all categories, all future prompts, rewrites included.

Get lifetime access

Card or PayPal · taxes at checkout · nothing to download

Not the one you need?

Browse every prompt by category and sub-category.

Browse all prompts
Lifetime $59 →