Skip to content
Lakeside read-only MCPDemo server · mocked upstream APIs

How it stays read-only

Nine checks between ClickUp's AI and the data

Every excerpt below is read from the repository at build time, so it is the code that is running. Short version: nothing in the server can send anything but GET to an allowlisted path, and no contact, bank, card or medical details leave it.

How it cannot modify or leak data, in three sentences

The server has no write tools: its only upstream client can send GET to a fixed list of Connecteam and ROLLER paths, a guard underneath blocks every other method and host, and the ROLLER key itself can be scoped to just those GET endpoints. Results are cut down to named fields, with contact, bank, card, tax file and Medicare details and medical flags removed before anything leaves the server. The API keys live only as Cloudflare secrets set by the team that deploys the server, and ClickUp connects with its own bearer token that can be rotated or revoked at any time.

What it does share

Staff names, rostered and clocked times, hours, labour totals and pay as department averages. That is what the questions need, and on a day one person worked a department alone, labour cost and hours together imply their rate. So who can use the connection in ClickUp decides who sees it: a personal (“Just for me”) connection keeps it to the person who adds it.

1. Only read tools are registered

The server registers nine tools and nothing else: no resources, no prompts, no create, update or delete tools, and no tool that takes a URL, path or HTTP method. Every tool carries the read-only, non-destructive and idempotent hints, the tool list is fixed (listChanged: false), and the integration tests fail if any of that changes.

src/mcp/server.ts · tool-registration
/** Every tool is declared read-only, non-destructive and idempotent. */
export const READ_ONLY_ANNOTATIONS = {
  readOnlyHint: true,
  destructiveHint: false,
  idempotentHint: true,
  openWorldHint: false,
} as const;

export function createMcpServer(
  ctx: ToolContext,
  options: { mode: UpstreamMode; tokenId?: string },
): McpServer {
  const server = new McpServer(SERVER_INFO, {
    capabilities: { tools: { listChanged: false } },
    instructions: serverInstructions(options.mode, ctx.timezone),
    jsonSchemaValidator: new CfWorkerJsonSchemaValidator(),
  });
  for (const tool of TOOLS) {
    server.registerTool(
      tool.name,
      {
        title: tool.title,
        description: tool.description,
        inputSchema: tool.input,
        annotations: { title: tool.title, ...READ_ONLY_ANNOTATIONS },
      },
      (args: unknown) => runTool(tool, args, ctx, options.mode, options.tokenId),
    );
  }
  // registerTool() advertises listChanged: true; this tool list never changes, so say so.
  server.server.registerCapabilities({ tools: { listChanged: false } });
  return server;
}
15 more lines

2. The upstream client can only GET allowlisted paths

Tools never call fetch directly. They go through ReadOnlyClient, whose only public method is get(). The path must match a fixed template list, so even a bug in a tool cannot reach an endpoint that writes.

src/upstream/http.ts · readonly-client
export class ReadOnlyClient {
  private readonly origin: string;
  private queue: Promise<unknown> = Promise.resolve();
  private lastCallAt = 0;

  constructor(private readonly options: ReadOnlyClientOptions) {
    this.origin = new URL(options.baseUrl).origin;
  }

  /** The only public way to reach an upstream API: GET, allowlisted paths only. */
  async get<T>(path: string, query: Record<string, QueryValue> = {}): Promise<T> {
    const rule = matchRule(path, this.options.rules);
    if (!rule) {
      const api = API_LABEL[this.options.api];
      throw new UpstreamPolicyError(`${api}: path is not on the read-only allowlist`);
    }
    const url = new URL(this.options.baseUrl.replace(/\/$/, "") + path);
    if (url.origin !== this.origin) {
      throw new UpstreamPolicyError("Upstream origin mismatch");
    }
    for (const [key, value] of Object.entries(query)) {
      if (value === undefined) continue;
      for (const item of Array.isArray(value) ? value : [value]) {
        url.searchParams.append(key, String(item));
      }
    }
    return this.send<T>("GET", url, rule, true);
  }

  private async send<T>(
    method: "GET",
    url: URL,
    rule: PathRule,
    retryOn401: boolean,
  ): Promise<T> {
    // Types can be bypassed at runtime; this check cannot.
    if (method !== "GET") {
      throw new UpstreamPolicyError(`Blocked ${String(method)}: upstream access is read-only`);
    }
    await this.throttle();
    const token = await this.options.tokens.getToken();
    const response = await this.options.fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
      redirect: "manual",
      signal: AbortSignal.timeout(this.options.timeoutMs ?? 15_000),
    });
    if (response.status === 401 && retryOn401) {
      // Reuse a token until the API rejects it, then fetch one new token and retry once.
      this.options.tokens.invalidate();
      return this.send<T>(method, url, rule, false);
    }
    if (!response.ok) {
      const api = API_LABEL[this.options.api];
      throw new UpstreamHttpError(
        this.options.api,
        response.status,
        `${api} returned HTTP ${response.status} for "${rule.name}"`,
      );
    }
    return (await response.json()) as T;
  }
44 more lines
src/upstream/workforce.ts · workforce-allowlist
export const WORKFORCE_RULES = pathRules([
  ["list users", "/users/v1/users"],
  ["list jobs", "/jobs/v1/jobs"],
  ["list schedulers", "/scheduler/v1/schedulers"],
  ["list scheduler shifts", "/scheduler/v2/schedulers/{schedulerId}/shifts"],
  ["list time clocks", "/time-clock/v1/time-clocks"],
  ["list time activities", "/time-clock/v1/time-clocks/{timeClockId}/time-activities"],
  ["get pay rates", "/pay-rates/v1/pay-rates"],
]);
src/upstream/booking.ts · booking-allowlist
export const BOOKING_RULES = pathRules([
  ["search bookings", "/bookings"],
  ["list products", "/data/products"],
  ["list booking payments", "/data/bookingpayments"],
  ["list revenue entries", "/reporting/revenue-entries"],
]);

3. A guard under the client blocks every other method

The fetch function the clients receive is wrapped once more. It lets GET through to the two API hosts and POST through to the two OAuth token URLs, and throws on anything else. The tests send POST, PUT, PATCH and DELETE through it to prove that.

src/upstream/http.ts · fetch-guard
export interface FetchPolicy {
  /** Origins that may receive GET requests. */
  apiOrigins: readonly string[];
  /** Exact URLs (origin + path) that may receive the OAuth token POST. */
  tokenUrls: readonly string[];
}

export function readOnlyFetch(inner: FetchLike, policy: FetchPolicy): FetchLike {
  return async (input, init) => {
    const request = new Request(input, init);
    const url = new URL(request.url);
    const target = `${url.origin}${url.pathname}`;
    const isTokenRequest = policy.tokenUrls.includes(target) && url.search === "";
    if (request.method === "POST" && isTokenRequest) {
      return inner(request);
    }
    if (request.method !== "GET") {
      throw new UpstreamPolicyError(
        `Blocked ${request.method} ${target}: upstream access is read-only`,
      );
    }
    if (!policy.apiOrigins.includes(url.origin)) {
      throw new UpstreamPolicyError(`Blocked request to unexpected host ${url.host}`);
    }
    return inner(request);
  };
}
9 more lines

4. Inputs are validated before any upstream call

Each tool has a Zod schema. Dates must be real calendar dates in YYYY-MM-DD form between 2000 and 2099, the end cannot precede the start, and a range is capped at 31 days. Enums and number bounds are checked the same way, and invalid input returns a readable tool error without touching an upstream API. Loops over dates count days rather than compare strings, so no input can keep one running.

src/tools/schemas.ts · date-range
/** A real calendar date in YYYY-MM-DD form, between 2000 and 2099. */
export function isoDate(description: string) {
  return z.iso
    .date()
    .refine((d) => d >= MIN_DATE && d <= MAX_DATE, { message: `Dates must be between ${MIN_DATE} and ${MAX_DATE}` })
    .describe(description);
}

const rangeShape = {
  start: isoDate("First day, venue-local, YYYY-MM-DD (inclusive)."),
  end: isoDate(`Last day, venue-local, YYYY-MM-DD (inclusive). The range may span at most ${MAX_RANGE_DAYS} days.`),
};

type Range = { start: string; end: string };

export function checkRange(value: Range, ctx: z.RefinementCtx): void {
  // Issues sit on the whole input so the message reads as a sentence on its own.
  const issue = (message: string) => ctx.addIssue({ code: "custom", path: [], message });
  if (value.end < value.start) {
    issue("end must be on or after start");
    return;
  }
  const days = daysInclusive(value.start, value.end);
  if (days > MAX_RANGE_DAYS) {
    issue(`Date range is limited to ${MAX_RANGE_DAYS} days per call; ${value.start} to ${value.end} is ${days} days. Split it into smaller ranges.`);
  }
}

/** A tool input with `start` and `end` dates, validated together. */
export function rangeInput<S extends z.ZodRawShape>(extra: S) {
  return z
    .object({ ...rangeShape, ...extra })
    .superRefine((value, ctx) => checkRange(value as Range, ctx));
}
16 more lines

5. Results carry named fields only, then get redacted again

Each tool copies named fields into its own output shape. list_staff returns only the custom fields a deployment names, get_timesheets shows hasNote instead of note text unless notes are switched on, medical guest flags are never returned, and totals keyed by data (payment methods, departments, categories) come back as arrays. A second layer then drops personal and financial keys wherever they appear and masks phone numbers, emails, bank, tax file and Medicare numbers inside free text.

src/core/redact.ts · redaction-rules
const SENSITIVE_KEY_PARTS = [
  "phone",
  "mobile",
  "email",
  "address",
  "birth",
  "bank",
  "iban",
  "swift",
  "accountnumber",
  "taxfile",
  "medicare",
  "creditcard",
  "cardnumber",
  "cardlast4",
  "kioskcode",
  "passcode",
  "giftcardnumber",
  "externalpaymentreference",
  "transactionid",
];
const SENSITIVE_KEYS_EXACT = new Set(["dob", "bsb", "tfn", "pin"]);

const EMAIL = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;
const OBFUSCATED_EMAIL = /[A-Z0-9._%+-]+\s*(?:\[at\]|\(at\)|\{at\})\s*[A-Z0-9-]+(?:\s*(?:\.|\[dot\]|\(dot\))\s*[A-Z0-9-]+)+/gi;
const AU_PHONE = /(?<![\w+])(?:\+?61[\s.-]?|\(?0)\s?[23478]\)?(?:[\s.-]?\d){8}(?!\d)/g;
const INTL_PHONE = /(?<![\w+])\+\d{1,3}(?:[\s.-]?\d){7,12}(?!\d)/g;
const BSB = /\bBSB\b[\s:#.-]*\d{3}[\s-]?\d{3}/gi;
const ACCOUNT_NO = /\b(?:acc(?:oun)?t?|a\/c)\.?(?:\s*(?:no\.?|number|#))?[\s.:#-]*\d{6,10}\b/gi;
const TAX_FILE_NO = /\b(?:TFN|tax file(?:\s+number)?)\b[\s:#.-]*(?:(?:is|no\.?|number)\s*)?\d{3}[\s.-]?\d{3}[\s.-]?\d{2,3}\b/gi;
const MEDICARE_NO = /\bMedicare\b(?:\s*(?:card|no\.?|number|#))*[\s:#.-]*\d{4}[\s-]?\d{5}[\s-]?\d(?:[\s-]?\d)?\b/gi;
13 more lines

6. Every request passes the same gate

Origin check against an explicit list (browser clients only), bearer token, method, a rate limit per token (and per visitor for the shared demo token), then the body: at most 64 KB and one JSON-RPC message. Batches were removed from MCP in 2025-06-18 and would let one request run many tool calls. The transport is stateless with JSON responses, so GET and DELETE get 405.

src/mcp/handler.ts · request-gate
const origin = request.headers.get("origin");
if (origin && !isAllowedOrigin(origin, url, rt.config.allowedOrigins)) {
  logEvent("origin_rejected", { method: request.method });
  return jsonRpcError(403, -32000, "Origin not allowed");
}

const auth = await verifyBearer(request.headers.get("authorization"), rt.tokens);
if (!auth.ok) {
  logEvent("auth_rejected", { reason: auth.reason, method: request.method });
  return jsonRpcError(401, -32001, "Missing or invalid bearer token", {
    "www-authenticate": 'Bearer realm="mcp"',
  });
}

if (request.method !== "POST") {
  // Stateless server: no SSE stream to open (GET) and no session to end (DELETE).
  return jsonRpcError(405, -32000, "Method not allowed. Send MCP messages with POST.", {
    allow: "POST",
  });
}

// A secret token is one connector's quota. The shared public demo token is
// limited per visitor as well, so one visitor cannot use it up for everyone.
const limitKey = auth.kind === "public-demo" ? `${auth.tokenId}:${clientAddress(request)}` : auth.tokenId;
const decision = await rt.limiter.check(limitKey);
if (!decision.allowed) {
  logEvent("rate_limited", { token: auth.tokenId });
  return jsonRpcError(429, -32000, "Rate limit exceeded for this token", {
    "retry-after": String(decision.retryAfter),
  });
}

const body = await readBody(request, MAX_BODY_BYTES);
if (body === undefined) return jsonRpcError(413, -32000, "Request body is larger than 64 KB");
// JSON-RPC batches were removed from MCP in 2025-06-18. One message per POST
// also means the rate limit above counts every tool call.
if (Array.isArray(parseJson(body))) {
  logEvent("batch_rejected", { token: auth.tokenId });
  return jsonRpcError(400, -32600, "Batch requests are not supported. Send one JSON-RPC message per POST.");
}
22 more lines

7. Tokens are compared in constant time

Both the presented token and each accepted token are hashed to 32 bytes and compared without an early exit. Logs and the rate limiter only ever see a short hash id, never the token.

src/core/auth.ts · constant-time
/** Constant-time comparison of two equal-length digests. */
export function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i += 1) diff |= a[i] ^ b[i];
  return diff === 0;
}

export async function verifyBearer(
  authorization: string | null,
  accepted: readonly AcceptedToken[],
): Promise<AuthResult> {
  if (!authorization) return { ok: false, reason: "missing" };
  const match = /^Bearer\s+([A-Za-z0-9._~+/=-]{8,512})\s*$/i.exec(authorization);
  if (!match) return { ok: false, reason: "malformed" };

  const presented = await sha256(match[1]);
  let found: AcceptedToken | undefined;
  for (const token of accepted) {
    // Compare against every token so timing does not reveal which one matched.
    if (timingSafeEqual(presented, token.digest) && !found) found = token;
  }
  if (!found) return { ok: false, reason: "invalid" };
  return { ok: true, tokenId: found.id, kind: found.kind };
}
src/core/rate-limit.ts · rate-limit
export class MemoryRateLimiter implements RateLimiter {
  private readonly hits = new Map<string, number[]>();

  constructor(
    private readonly limit: number,
    private readonly windowMs: number,
    private readonly now: () => number = Date.now,
  ) {}

  async check(key: string): Promise<RateDecision> {
    const now = this.now();
    const recent = (this.hits.get(key) ?? []).filter((t) => now - t < this.windowMs);
    if (recent.length >= this.limit) {
      this.hits.set(key, recent);
      const retryAfter = Math.max(1, Math.ceil((recent[0] + this.windowMs - now) / 1000));
      return { allowed: false, retryAfter };
    }
    recent.push(now);
    this.hits.set(key, recent);
    if (this.hits.size > 5_000) this.prune(now);
    return { allowed: true, retryAfter: 0 };
  }

  private prune(now: number) {
    for (const [key, times] of this.hits) {
      if (times.every((t) => now - t >= this.windowMs)) this.hits.delete(key);
    }
  }
}
11 more lines

8. Upstream OAuth tokens are cached until they expire

Both APIs use OAuth 2.0 client credentials. Tokens are reused until shortly before expiry, concurrent callers share one token request, and a 401 triggers exactly one refresh and retry. ROLLER's docs warn that requesting a token per call can get credentials suspended.

src/upstream/oauth.ts · token-cache
export class ClientCredentialsTokenSource implements TokenSource {
  private cached?: { token: string; expiresAt: number };
  private inflight?: Promise<string>;
  /** Number of token requests made, exposed for tests and diagnostics. */
  requestCount = 0;

  constructor(private readonly options: TokenSourceOptions) {}

  private now(): number {
    return (this.options.now ?? Date.now)();
  }

  async getToken(): Promise<string> {
    if (this.cached && this.now() < this.cached.expiresAt) return this.cached.token;
    // Concurrent callers share one in-flight token request.
    this.inflight ??= this.requestToken().finally(() => {
      this.inflight = undefined;
    });
    return this.inflight;
  }

  invalidate(): void {
    this.cached = undefined;
  }

9. Fictional data is never served by accident

UPSTREAM_MODE must be exactly mock or live. Real API credentials or secret tokens force it to be set, and mock mode refuses to start next to real credentials. Every result also carries a dataSource field, so an assistant can tell the demo data from a venue's real figures.

src/core/config.ts · upstream-mode
/**
 * Mock mode serves fictional data, so it is never a silent fallback: the value
 * must be exactly mock or live (any case), and real API credentials or secret
 * bearer tokens require the mode to be set explicitly.
 */
export function parseUpstreamMode(env: EnvSource): UpstreamMode {
  const raw = str(env, "UPSTREAM_MODE");
  const hasCredentials = REAL_CREDENTIAL_KEYS.some((key) => str(env, key) !== undefined);
  if (raw === undefined) {
    if (hasCredentials || str(env, "MCP_BEARER_TOKENS") !== undefined) {
      throw new ConfigError("Set UPSTREAM_MODE to live (or mock for the fictional demo data)");
    }
    return "mock";
  }
  const mode = raw.toLowerCase();
  if (mode !== "mock" && mode !== "live") throw new ConfigError('UPSTREAM_MODE must be "mock" or "live"');
  if (mode === "mock" && hasCredentials) {
    throw new ConfigError("API credentials are set but UPSTREAM_MODE is mock; refusing to serve fictional data");
  }
  return mode;
}

Tool to upstream endpoint

Every upstream call is a GET. ROLLER reports are fetched one day at a time.

  • list_staff

    • Connecteam GET /users/v1/users
  • get_schedules

    • Connecteam GET /scheduler/v1/schedulers
    • Connecteam GET /scheduler/v2/schedulers/{schedulerId}/shifts
    • Connecteam GET /users/v1/users
    • Connecteam GET /jobs/v1/jobs
  • get_timesheets

    • Connecteam GET /time-clock/v1/time-clocks
    • Connecteam GET /time-clock/v1/time-clocks/{timeClockId}/time-activities
    • Connecteam GET /users/v1/users
    • Connecteam GET /jobs/v1/jobs
  • get_pay_rates

    • Connecteam GET /pay-rates/v1/pay-rates
    • Connecteam GET /users/v1/users
    • Connecteam GET /jobs/v1/jobs
  • list_bookings

    • ROLLER GET /bookings?date={date} (one call per day)
    • ROLLER GET /data/products
  • list_products

    • ROLLER GET /data/products
  • get_transactions

    • ROLLER GET /data/bookingpayments (one call per day)
  • get_revenue_report

    • ROLLER GET /reporting/revenue-entries (one call per day)
    • ROLLER GET /data/products
  • labour_cost_percent

    • Connecteam GET /time-clock/v1/time-clocks
    • Connecteam GET /time-clock/v1/time-clocks/{timeClockId}/time-activities
    • Connecteam GET /pay-rates/v1/pay-rates
    • Connecteam GET /jobs/v1/jobs
    • ROLLER GET /reporting/revenue-entries (one call per day)

What the mocks copy from public docs, and what gets confirmed

Built from Connecteam's API reference and ROLLER's published OpenAPI files. The items under “to confirm” are assumptions until they are checked against a real account.

Connecteam (AU region)

Confirmed in public docs

  • OAuth 2.0 client credentials: POST /oauth/v1/token, HTTP Basic client authentication, grant_type=client_credentials
  • Australian accounts use the api-au.connecteam.com host
  • Paths for users, jobs, schedulers, shifts (v2), time clocks, time activities and pay rates, with { requestId, data, paging } envelopes
  • Pay-rate queries need startDate and endDate, at most 365 days apart; scopes schedule.read and pay_rates.read

To confirm against a real account

  • Token lifetime of 24 hours
  • Scope names users.read, jobs.read and time_clock.read
  • How departments are set up: jobs, plus a 'Department' custom field on each user
  • Manual breaks are unpaid; award penalty rates come from timesheet pay items, not the pay-rates endpoint

ROLLER

Confirmed in public docs

  • POST https://api.roller.app/token with a JSON body of client_id and client_secret, returning a Bearer token with expires_in (generally 24 hours)
  • Reuse the token until a 401; one set of credentials per venue; one call per second
  • API keys scoped to specific endpoints; restricted endpoints answer 403 INSUFFICIENT_SCOPE
  • GET /bookings (search, up to 100 results), /data/products, /data/bookingpayments and /reporting/revenue-entries, with date filters of at most one day

To confirm against a real account

  • Reporting endpoints return a plain JSON array, 100 entries per page
  • Endpoints outside a key's scope also answer 403 INSUFFICIENT_SCOPE
  • Field subsets and value formats beyond the documented examples

Secrets and logs

  • Bearer tokens and both sets of API credentials are read from the environment only: Worker secrets on Cloudflare, encrypted environment variables here.
  • In live mode the server refuses to start without a secret token of at least 32 characters, and the public demo token is switched off.
  • Logs are single JSON lines with the tool name, duration, outcome, dates queried and a token hash id. The logger only accepts primitive values, so a result or request body cannot be passed to it.
  • Upstream error bodies are never forwarded. A tool error says which API and status failed, nothing more.