untappd-mcp 2.1.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -1585,8 +1585,8 @@ var require_regexes = __commonJS({
1585
1585
  }
1586
1586
  exports.ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1587
1587
  exports.ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
1588
- var mac3 = (delimiter) => {
1589
- const escapedDelim = util.escapeRegex(delimiter ?? ":");
1588
+ var mac3 = (delimiter2) => {
1589
+ const escapedDelim = util.escapeRegex(delimiter2 ?? ":");
1590
1590
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
1591
1591
  };
1592
1592
  exports.mac = mac3;
@@ -5000,7 +5000,7 @@ var require_memoizer = __commonJS({
5000
5000
  return bucket;
5001
5001
  }
5002
5002
  var handoff2;
5003
- var open2 = [];
5003
+ var open3 = [];
5004
5004
  var memo3 = {
5005
5005
  alloc(_inst, payload, empty) {
5006
5006
  const bucket = handoff2;
@@ -5009,7 +5009,7 @@ var require_memoizer = __commonJS({
5009
5009
  handoff2 = void 0;
5010
5010
  const entry = { value: empty, issues: null };
5011
5011
  bucket.set(payload.value, entry);
5012
- open2.push(entry);
5012
+ open3.push(entry);
5013
5013
  return empty;
5014
5014
  },
5015
5015
  guard(inst) {
@@ -5080,10 +5080,10 @@ var require_memoizer = __commonJS({
5080
5080
  return payload;
5081
5081
  }
5082
5082
  handoff2 = bucket;
5083
- const depth = open2.length;
5083
+ const depth = open3.length;
5084
5084
  const result = base(payload, ctx);
5085
5085
  handoff2 = void 0;
5086
- const entry = open2.length > depth ? open2.pop() : void 0;
5086
+ const entry = open3.length > depth ? open3.pop() : void 0;
5087
5087
  if (result instanceof Promise) {
5088
5088
  return result.then((r) => {
5089
5089
  if (entry)
@@ -23315,6 +23315,33 @@ var storage2 = new AsyncLocalStorage2();
23315
23315
  function withCallerCapabilities(capabilities, fn) {
23316
23316
  return capabilities ? storage2.run(capabilities, fn) : fn();
23317
23317
  }
23318
+ function currentCallerCapabilities() {
23319
+ return storage2.getStore();
23320
+ }
23321
+ var ENVELOPE_CAPABILITIES_KEY = "io.modelcontextprotocol/clientCapabilities";
23322
+ var ELICITATION_MODES = ["form", "url"];
23323
+ function isRecord(value) {
23324
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23325
+ }
23326
+ function callerCapabilities(ctx) {
23327
+ const envelope = isRecord(ctx) && isRecord(ctx.mcpReq) ? ctx.mcpReq.envelope : void 0;
23328
+ if (isRecord(envelope)) {
23329
+ const declared = envelope[ENVELOPE_CAPABILITIES_KEY];
23330
+ if (isRecord(declared))
23331
+ return declared;
23332
+ }
23333
+ return currentCallerCapabilities();
23334
+ }
23335
+ function callerAcceptsFormElicitation(ctx) {
23336
+ const capabilities = callerCapabilities(ctx);
23337
+ if (!capabilities)
23338
+ return void 0;
23339
+ const elicitation = capabilities.elicitation;
23340
+ if (!isRecord(elicitation))
23341
+ return false;
23342
+ const namedModes = ELICITATION_MODES.filter((mode) => mode in elicitation);
23343
+ return namedModes.length === 0 || namedModes.includes("form");
23344
+ }
23318
23345
 
23319
23346
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
23320
23347
  var __create2 = Object.create;
@@ -27713,6 +27740,37 @@ var inputRequired = Object.assign(buildInputRequired, {
27713
27740
  return { method: "roots/list" };
27714
27741
  }
27715
27742
  });
27743
+ function acceptedContent(responses, key, schema) {
27744
+ const view = inputResponse(responses, key);
27745
+ if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0;
27746
+ if (schema === void 0) return view.content;
27747
+ const outcome = schema["~standard"].validate(view.content);
27748
+ if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema");
27749
+ return outcome.issues === void 0 ? outcome.value : void 0;
27750
+ }
27751
+ function inputResponse(responses, key) {
27752
+ if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" };
27753
+ const entry = responses[key];
27754
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" };
27755
+ const candidate = entry;
27756
+ if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") {
27757
+ const content = candidate["content"];
27758
+ return {
27759
+ kind: "elicit",
27760
+ action: candidate["action"],
27761
+ ...content !== null && typeof content === "object" && !Array.isArray(content) && { content }
27762
+ };
27763
+ }
27764
+ if (Array.isArray(candidate["roots"])) return {
27765
+ kind: "roots",
27766
+ roots: candidate["roots"]
27767
+ };
27768
+ if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return {
27769
+ kind: "sampling",
27770
+ result: candidate
27771
+ };
27772
+ return { kind: "missing" };
27773
+ }
27716
27774
  var REQUEST_STATE_ONLY_LEG_PACING_MS = 250;
27717
27775
  function inputRequiredRoundsExceededMessage(method, maxRounds) {
27718
27776
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
@@ -37760,14 +37818,14 @@ function serveStdio(factory, options = {}) {
37760
37818
  return false;
37761
37819
  };
37762
37820
  const answerLegacyRejection = (request, reason, requestedVersion) => {
37763
- const rejection2 = modernOnlyStrictRejection({
37821
+ const rejection3 = modernOnlyStrictRejection({
37764
37822
  kind: "legacy",
37765
37823
  reason,
37766
37824
  ...requestedVersion !== void 0 && { requestedVersion }
37767
37825
  }, SUPPORTED_MODERN_PROTOCOL_VERSIONS);
37768
- if (rejection2 === void 0) return Promise.resolve();
37769
- reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection2.cell}): ${rejection2.message}`));
37770
- return writeErrorResponse(request.id, rejection2.code, rejection2.message, rejection2.data);
37826
+ if (rejection3 === void 0) return Promise.resolve();
37827
+ reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection3.cell}): ${rejection3.message}`));
37828
+ return writeErrorResponse(request.id, rejection3.code, rejection3.message, rejection3.data);
37771
37829
  };
37772
37830
  const onInstanceClosed = (channel) => {
37773
37831
  if (closing || channel === discarding) return;
@@ -40052,8 +40110,8 @@ function emoji() {
40052
40110
  }
40053
40111
  var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
40054
40112
  var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
40055
- var mac = (delimiter) => {
40056
- const escapedDelim = escapeRegex(delimiter ?? ":");
40113
+ var mac = (delimiter2) => {
40114
+ const escapedDelim = escapeRegex(delimiter2 ?? ":");
40057
40115
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
40058
40116
  };
40059
40117
  var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
@@ -57758,6 +57816,11 @@ var MEDIA_QUALIFIER = "(?:primary|secondary|main|default|cover|hero|profile|mast
57758
57816
  var MEDIA_KEY = new RegExp(`^(?:(?:${MEDIA_QUALIFIER}|${MEDIA_NOUN})[_-]?)?${MEDIA_NOUN}s?(?:[_-]?(?:link|uri|url|src)s?)?$`, "i");
57759
57817
 
57760
57818
  // node_modules/@chrischall/mcp-utils/dist/response/index.js
57819
+ function textResult(data) {
57820
+ return {
57821
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
57822
+ };
57823
+ }
57761
57824
  function errorResult(message) {
57762
57825
  return {
57763
57826
  content: [{ type: "text", text: redactSecrets(message) }],
@@ -57765,6 +57828,418 @@ function errorResult(message) {
57765
57828
  };
57766
57829
  }
57767
57830
 
57831
+ // node_modules/@chrischall/mcp-utils/dist/server/confirmation.js
57832
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
57833
+
57834
+ // node_modules/@chrischall/mcp-utils/dist/server/canonical.js
57835
+ function canonicalJson(value) {
57836
+ if (value === null || typeof value === "string" || typeof value === "boolean")
57837
+ return JSON.stringify(value);
57838
+ if (value === void 0)
57839
+ return "null";
57840
+ if (typeof value === "number")
57841
+ return Number.isFinite(value) ? JSON.stringify(value) : `{"$num":"${String(value)}"}`;
57842
+ if (typeof value === "bigint")
57843
+ return `{"$bigint":"${value.toString()}"}`;
57844
+ if (typeof value === "function" || typeof value === "symbol") {
57845
+ throw new TypeError(`confirmation: cannot bind a ${typeof value} argument value.`);
57846
+ }
57847
+ if (Array.isArray(value))
57848
+ return `[${value.map(canonicalJson).join(",")}]`;
57849
+ if (value instanceof Date) {
57850
+ return `{"$date":${JSON.stringify(Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString())}}`;
57851
+ }
57852
+ if (ArrayBuffer.isView(value)) {
57853
+ const bytes = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
57854
+ return `{"$bytes":${JSON.stringify(bytes.toString("base64"))}}`;
57855
+ }
57856
+ if (value instanceof ArrayBuffer)
57857
+ return `{"$bytes":${JSON.stringify(Buffer.from(value).toString("base64"))}}`;
57858
+ if (value instanceof Map) {
57859
+ const entries2 = [...value.entries()].map(([k, v]) => `[${canonicalJson(k)},${canonicalJson(v)}]`).sort();
57860
+ return `{"$map":[${entries2.join(",")}]}`;
57861
+ }
57862
+ if (value instanceof Set) {
57863
+ return `{"$set":[${[...value].map(canonicalJson).sort().join(",")}]}`;
57864
+ }
57865
+ const proto = Object.getPrototypeOf(value);
57866
+ if (proto !== Object.prototype && proto !== null) {
57867
+ throw new TypeError("confirmation: cannot bind a non-plain object argument value (class instance).");
57868
+ }
57869
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
57870
+ return `{${entries.map(([k, v]) => `${JSON.stringify(escapeKey(k))}:${canonicalJson(v)}`).join(",")}}`;
57871
+ }
57872
+ function escapeKey(key) {
57873
+ return key.startsWith("$") ? `$${key}` : key;
57874
+ }
57875
+
57876
+ // node_modules/@chrischall/mcp-utils/dist/server/confirmation.js
57877
+ var DEFAULT_REQUEST_KEY = "confirmation";
57878
+ var DEFAULT_CONFIRMATION_LABEL = "Confirm this action should proceed.";
57879
+ var UNSUPPORTED_NOTE = "Nothing was done because this client cannot show a confirmation prompt (it declares no MCP elicitation capability), and this action is never taken without one";
57880
+ var STATE_PREFIX = "mcpu.confirm.v1.";
57881
+ function bindingKey(binding) {
57882
+ if (binding.ttlSeconds !== void 0 && !(Number.isFinite(binding.ttlSeconds) && binding.ttlSeconds > 0)) {
57883
+ throw new RangeError("requireConfirmation: binding.ttlSeconds must be a finite number greater than 0.");
57884
+ }
57885
+ const key = typeof binding.key === "string" ? Buffer.from(binding.key, "utf8") : Buffer.from(binding.key);
57886
+ if (key.length < 32) {
57887
+ throw new RangeError("requireConfirmation: binding.key must be at least 32 bytes.");
57888
+ }
57889
+ return key;
57890
+ }
57891
+ function commitment(action, args) {
57892
+ return createHash("sha256").update(`${action}\0${canonicalJson(args)}`).digest("base64url");
57893
+ }
57894
+ function mintState(key, action, binding) {
57895
+ const exp = Math.floor(Date.now() / 1e3) + (binding.ttlSeconds ?? 600);
57896
+ const body = Buffer.from(JSON.stringify({ c: commitment(action, binding.args), exp })).toString("base64url");
57897
+ const mac3 = createHmac("sha256", key).update(`${STATE_PREFIX}${body}`).digest("base64url");
57898
+ return `${STATE_PREFIX}${body}.${mac3}`;
57899
+ }
57900
+ function verifyState(key, action, binding, state) {
57901
+ if (typeof state !== "string" || !state.startsWith(STATE_PREFIX))
57902
+ return false;
57903
+ const rest = state.slice(STATE_PREFIX.length);
57904
+ const dot = rest.indexOf(".");
57905
+ if (dot < 0)
57906
+ return false;
57907
+ const body = rest.slice(0, dot);
57908
+ const mac3 = Buffer.from(rest.slice(dot + 1), "base64url");
57909
+ const expected = createHmac("sha256", key).update(`${STATE_PREFIX}${body}`).digest();
57910
+ if (mac3.length !== expected.length || !timingSafeEqual(mac3, expected))
57911
+ return false;
57912
+ let payload;
57913
+ try {
57914
+ payload = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
57915
+ } catch {
57916
+ return false;
57917
+ }
57918
+ if (typeof payload.exp !== "number" || payload.exp * 1e3 <= Date.now())
57919
+ return false;
57920
+ const want = Buffer.from(commitment(action, binding.args));
57921
+ const got = Buffer.from(typeof payload.c === "string" ? payload.c : "");
57922
+ return got.length === want.length && timingSafeEqual(got, want);
57923
+ }
57924
+ function echoedState(ctx) {
57925
+ const accessor = ctx.mcpReq.requestState;
57926
+ return typeof accessor === "function" ? accessor() : void 0;
57927
+ }
57928
+ function requireConfirmation(ctx, options) {
57929
+ const requestKey = options.requestKey ?? DEFAULT_REQUEST_KEY;
57930
+ const key = options.binding ? bindingKey(options.binding) : void 0;
57931
+ const confirmationSchema = external_exports.object({
57932
+ confirmed: external_exports.boolean().describe(options.confirmationLabel ?? DEFAULT_CONFIRMATION_LABEL)
57933
+ });
57934
+ const ask = () => {
57935
+ const preview = {
57936
+ action: options.action,
57937
+ ...options.details === void 0 ? {} : { details: options.details }
57938
+ };
57939
+ return inputRequired({
57940
+ inputRequests: {
57941
+ [requestKey]: inputRequired.elicit({
57942
+ message: `${options.message}
57943
+ ${JSON.stringify(preview, null, 2)}`,
57944
+ requestedSchema: confirmationSchema
57945
+ })
57946
+ },
57947
+ ...key && options.binding ? { requestState: mintState(key, options.action, options.binding) } : {}
57948
+ });
57949
+ };
57950
+ const response = inputResponse(ctx.mcpReq.inputResponses, requestKey);
57951
+ const accepted = acceptedContent(ctx.mcpReq.inputResponses, requestKey, confirmationSchema);
57952
+ if (response.kind === "missing") {
57953
+ if (callerAcceptsFormElicitation(ctx) === false) {
57954
+ return textResult({
57955
+ confirmed: false,
57956
+ dispatched: false,
57957
+ action: options.action,
57958
+ reason: "confirmation-unsupported",
57959
+ note: options.unsupportedNote ? `${UNSUPPORTED_NOTE}. ${options.unsupportedNote}` : `${UNSUPPORTED_NOTE}.`
57960
+ });
57961
+ }
57962
+ return ask();
57963
+ }
57964
+ if (response.kind === "elicit" && response.action === "accept" && accepted?.confirmed === true) {
57965
+ if (key && options.binding) {
57966
+ const state = echoedState(ctx);
57967
+ if (state === void 0 || state === null) {
57968
+ return errorResult(`Confirmation for ${options.action} was accepted, but the retry carried no requestState, so it cannot be checked against the prompt that was shown. Nothing was done. The likely cause is that the MCP client or host does not round-trip requestState (it must echo the requestState from the input_required result back on the retry); asking again would loop.`);
57969
+ }
57970
+ if (!verifyState(key, options.action, options.binding, state))
57971
+ return ask();
57972
+ }
57973
+ return void 0;
57974
+ }
57975
+ return textResult({
57976
+ confirmed: false,
57977
+ cancelled: true,
57978
+ action: options.action,
57979
+ note: "Nothing was changed because the confirmation was declined, cancelled, or left unchecked."
57980
+ });
57981
+ }
57982
+
57983
+ // node_modules/@chrischall/mcp-utils/dist/server/confirm-token.js
57984
+ import { createHash as createHash2, createHmac as createHmac2, randomBytes, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
57985
+ function createSpentTokenStore() {
57986
+ const spent = /* @__PURE__ */ new Map();
57987
+ return {
57988
+ has: (nonce) => spent.has(nonce),
57989
+ add: (nonce, exp) => {
57990
+ spent.set(nonce, exp);
57991
+ },
57992
+ prune: (now) => {
57993
+ for (const [nonce, exp] of spent)
57994
+ if (exp < now)
57995
+ spent.delete(nonce);
57996
+ },
57997
+ clear: () => spent.clear(),
57998
+ get size() {
57999
+ return spent.size;
58000
+ }
58001
+ };
58002
+ }
58003
+ var PROCESS_SPENT = createSpentTokenStore();
58004
+ var PREFIX = "mcpu.token.v1.";
58005
+ var DEFAULT_TTL_SECONDS = 600;
58006
+ function tokenKey(key) {
58007
+ const bytes = typeof key === "string" ? Buffer.from(key, "utf8") : Buffer.from(key);
58008
+ if (bytes.length < 32)
58009
+ throw new RangeError("confirm token: key must be at least 32 bytes.");
58010
+ return bytes;
58011
+ }
58012
+ function ttlOf(ttlSeconds) {
58013
+ if (ttlSeconds === void 0)
58014
+ return DEFAULT_TTL_SECONDS;
58015
+ if (!(Number.isFinite(ttlSeconds) && ttlSeconds > 0)) {
58016
+ throw new RangeError("confirm token: ttlSeconds must be a finite number greater than 0.");
58017
+ }
58018
+ return ttlSeconds;
58019
+ }
58020
+ function sign(key, body) {
58021
+ return createHmac2("sha256", key).update(`${PREFIX}${body}`).digest();
58022
+ }
58023
+ function hashConfirmPayload(payload) {
58024
+ return createHash2("sha256").update(canonicalJson(payload)).digest("base64url");
58025
+ }
58026
+ function issueConfirmToken(key, binding, options = {}) {
58027
+ const k = tokenKey(key);
58028
+ const now = options.now ?? Date.now();
58029
+ const exp = now + ttlOf(options.ttlSeconds) * 1e3;
58030
+ const claims = {
58031
+ t: binding.tool,
58032
+ ...binding.account === void 0 ? {} : { a: binding.account },
58033
+ g: binding.target,
58034
+ ...binding.revision === void 0 ? {} : { r: binding.revision },
58035
+ h: binding.payloadHash,
58036
+ exp,
58037
+ n: randomBytes(16).toString("base64url")
58038
+ };
58039
+ const body = Buffer.from(JSON.stringify(claims), "utf8").toString("base64url");
58040
+ return { token: `${PREFIX}${body}.${sign(k, body).toString("base64url")}`, expiresAt: new Date(exp).toISOString() };
58041
+ }
58042
+ function parseClaims(body) {
58043
+ try {
58044
+ const claims = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
58045
+ return claims && typeof claims === "object" ? claims : void 0;
58046
+ } catch {
58047
+ return void 0;
58048
+ }
58049
+ }
58050
+ function verifyConfirmToken(key, token, binding, options = {}) {
58051
+ const k = tokenKey(key);
58052
+ const now = options.now ?? Date.now();
58053
+ const spent = options.spent ?? PROCESS_SPENT;
58054
+ spent.prune(now);
58055
+ if (!token.startsWith(PREFIX))
58056
+ return { ok: false, error: "TOKEN_INVALID" };
58057
+ const rest = token.slice(PREFIX.length);
58058
+ const dot = rest.indexOf(".");
58059
+ const body = dot < 0 ? "" : rest.slice(0, dot);
58060
+ const mac3 = Buffer.from(dot < 0 ? "" : rest.slice(dot + 1), "base64url");
58061
+ const expected = sign(k, body);
58062
+ if (!body || mac3.length !== expected.length || !timingSafeEqual2(mac3, expected))
58063
+ return { ok: false, error: "TOKEN_INVALID" };
58064
+ const claims = parseClaims(body);
58065
+ if (!claims)
58066
+ return { ok: false, error: "TOKEN_INVALID" };
58067
+ if (claims.t !== binding.tool || claims.a !== binding.account || claims.g !== binding.target) {
58068
+ return { ok: false, error: "TOKEN_INVALID" };
58069
+ }
58070
+ if (spent.has(claims.n))
58071
+ return { ok: false, error: "TOKEN_REUSED" };
58072
+ if (now > claims.exp)
58073
+ return { ok: false, error: "TOKEN_EXPIRED" };
58074
+ if (claims.r !== binding.revision)
58075
+ return { ok: false, error: "DRAFT_CHANGED", reason: "revision-changed" };
58076
+ if (claims.h !== binding.payloadHash)
58077
+ return { ok: false, error: "DRAFT_CHANGED", reason: "payload-changed" };
58078
+ spent.add(claims.n, claims.exp);
58079
+ return { ok: true };
58080
+ }
58081
+ var CONFIRM_TOKEN_INSTRUCTION = "Show this preview to the user verbatim and proceed only after they explicitly approve in chat. Then call again with confirmToken.";
58082
+ var confirmTokenParam = external_exports.string().optional().describe(`ONLY for the two-step confirmation fallback (a client without MCP elicitation). The confirmToken from this same tool's phase-1 "confirmation-required" response, passed back ONLY after the user has seen that preview and explicitly approved it in chat \u2014 never on the first call, never invented, never reused. Call again with the same arguments. Ignored when the client supports elicitation.`);
58083
+ var TOKEN_ERROR_NOTE = {
58084
+ TOKEN_EXPIRED: "Nothing was sent or changed: the confirmToken expired. Call again WITHOUT confirmToken for a fresh preview, and ask the user to approve it again.",
58085
+ TOKEN_REUSED: "Nothing was sent or changed by this call: this confirmToken was already used, and one approval acts once. If doing it again is really intended, call again WITHOUT confirmToken and get a new approval.",
58086
+ TOKEN_INVALID: "Nothing was sent or changed: this confirmToken was not issued by this server for this tool, account and target (or the server has restarted since). Call again WITHOUT confirmToken for a fresh preview and approval."
58087
+ };
58088
+ var CHANGED_NOTE = {
58089
+ "revision-changed": "Nothing was sent or changed: the target was edited since the user approved it (its version rotated), so what would happen is not what they saw.",
58090
+ "payload-changed": "Nothing was sent or changed: what would happen no longer matches what the user approved."
58091
+ };
58092
+ function isToolResult(value) {
58093
+ return Array.isArray(value.content);
58094
+ }
58095
+ function rejection2(data) {
58096
+ return { ...textResult({ status: "confirmation-rejected", confirmed: false, dispatched: false, ...data }), isError: true };
58097
+ }
58098
+ async function tokenConfirmation(action, fb) {
58099
+ const subject = await fb.subject();
58100
+ if (isToolResult(subject))
58101
+ return subject;
58102
+ const binding = {
58103
+ tool: fb.tool,
58104
+ ...fb.account === void 0 ? {} : { account: fb.account },
58105
+ target: subject.target,
58106
+ ...subject.revision === void 0 ? {} : { revision: subject.revision },
58107
+ payloadHash: hashConfirmPayload(subject.payload)
58108
+ };
58109
+ const phaseOne = () => {
58110
+ const { token, expiresAt } = issueConfirmToken(fb.key, binding, { ttlSeconds: fb.ttlSeconds });
58111
+ return {
58112
+ action,
58113
+ preview: subject.preview,
58114
+ confirmToken: token,
58115
+ expiresAt,
58116
+ ttlSeconds: ttlOf(fb.ttlSeconds),
58117
+ instruction: fb.instruction ?? CONFIRM_TOKEN_INSTRUCTION
58118
+ };
58119
+ };
58120
+ if (!fb.confirmToken) {
58121
+ return textResult({ status: "confirmation-required", confirmed: false, dispatched: false, ...phaseOne() });
58122
+ }
58123
+ const verdict = verifyConfirmToken(fb.key, fb.confirmToken, binding, { spent: fb.spent });
58124
+ if (verdict.ok)
58125
+ return void 0;
58126
+ if (verdict.error === "DRAFT_CHANGED") {
58127
+ return rejection2({
58128
+ error: "DRAFT_CHANGED",
58129
+ reason: verdict.reason,
58130
+ note: `${CHANGED_NOTE[verdict.reason]} The current preview and a fresh confirmToken are below.`,
58131
+ ...phaseOne()
58132
+ });
58133
+ }
58134
+ return rejection2({ error: verdict.error, action, note: TOKEN_ERROR_NOTE[verdict.error] });
58135
+ }
58136
+ async function requireConfirmationWithFallback(ctx, options) {
58137
+ const { tokenFallback, ...confirmation } = options;
58138
+ if (tokenFallback && callerAcceptsFormElicitation(ctx) === false) {
58139
+ return tokenConfirmation(options.action, tokenFallback);
58140
+ }
58141
+ return requireConfirmation(ctx, confirmation);
58142
+ }
58143
+
58144
+ // node_modules/@chrischall/mcp-utils/dist/server/confirm-env.js
58145
+ import { createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
58146
+
58147
+ // node_modules/@chrischall/mcp-utils/dist/config/index.js
58148
+ import { homedir } from "node:os";
58149
+ import { isAbsolute, join, resolve } from "node:path";
58150
+ var PLACEHOLDER_RE = /^\$\{[^}]*\}$/;
58151
+ function readEnvVar(key, opts = {}) {
58152
+ const env = opts.env ?? process.env;
58153
+ const raw = env[key];
58154
+ if (typeof raw === "string") {
58155
+ const trimmed = raw.trim();
58156
+ if (trimmed.length > 0 && trimmed !== "undefined" && trimmed !== "null" && !PLACEHOLDER_RE.test(trimmed)) {
58157
+ return trimmed;
58158
+ }
58159
+ }
58160
+ return opts.default;
58161
+ }
58162
+ function expandPath(p) {
58163
+ let expanded = p;
58164
+ if (p === "~") {
58165
+ expanded = homedir();
58166
+ } else if (p.startsWith("~/")) {
58167
+ expanded = join(homedir(), p.slice(2));
58168
+ }
58169
+ return isAbsolute(expanded) ? expanded : resolve(expanded);
58170
+ }
58171
+ async function loadDotenvSafely(opts = {}) {
58172
+ try {
58173
+ const mod = await import(
58174
+ /* @vite-ignore */
58175
+ "dotenv"
58176
+ );
58177
+ const result = mod.config({
58178
+ ...opts.path !== void 0 ? { path: opts.path } : {},
58179
+ override: opts.override ?? false,
58180
+ quiet: true
58181
+ });
58182
+ return result.error === void 0;
58183
+ } catch {
58184
+ return false;
58185
+ }
58186
+ }
58187
+
58188
+ // node_modules/@chrischall/mcp-utils/dist/server/confirm-env.js
58189
+ var MODES = /* @__PURE__ */ new Set(["ask-user", "auto", "refuse"]);
58190
+ var DEFAULT_TTL_SECONDS2 = 600;
58191
+ var warned = /* @__PURE__ */ new Set();
58192
+ function readConfirmMode(env = process.env) {
58193
+ const raw = readEnvVar("MCP_CONFIRM_MODE", { env })?.trim().toLowerCase();
58194
+ if (!raw)
58195
+ return "ask-user";
58196
+ if (MODES.has(raw))
58197
+ return raw;
58198
+ if (!warned.has(raw)) {
58199
+ warned.add(raw);
58200
+ process.stderr.write(`MCP_CONFIRM_MODE="${raw}" is not one of ask-user, auto, refuse; treating it as refuse.
58201
+ `);
58202
+ }
58203
+ return "refuse";
58204
+ }
58205
+ function confirmTtlFromEnv(env = process.env) {
58206
+ const raw = readEnvVar("MCP_CONFIRM_TTL_SECONDS", { env })?.trim();
58207
+ return raw && /^[1-9]\d*$/.test(raw) ? Number(raw) : DEFAULT_TTL_SECONDS2;
58208
+ }
58209
+ var processKey;
58210
+ function confirmKeyFromEnv(env = process.env) {
58211
+ const secret = readEnvVar("MCP_CONFIRM_SECRET", { env });
58212
+ if (secret)
58213
+ return createHash3("sha256").update(secret, "utf8").digest();
58214
+ processKey ??= randomBytes2(32);
58215
+ return processKey;
58216
+ }
58217
+ var CONFIRM_TOKEN_AUTO_INSTRUCTION = "Nothing has been done yet. Review this preview; if it is what was intended, call again with the same arguments plus confirmToken. (This server runs with MCP_CONFIRM_MODE=auto, so the user's approval in chat is not required.)";
58218
+ var REFUSE_HINT = "Set MCP_CONFIRM_MODE=ask-user on the server to allow two-step confirmation instead.";
58219
+ function confirmationFromEnv(options) {
58220
+ const { tool, account, confirmToken, subject, instruction, spent, env = process.env, ...confirmation } = options;
58221
+ const mode = readConfirmMode(env);
58222
+ if (mode === "refuse") {
58223
+ return {
58224
+ ...confirmation,
58225
+ unsupportedNote: confirmation.unsupportedNote ? `${confirmation.unsupportedNote} ${REFUSE_HINT}` : REFUSE_HINT
58226
+ };
58227
+ }
58228
+ return {
58229
+ ...confirmation,
58230
+ tokenFallback: {
58231
+ key: confirmKeyFromEnv(env),
58232
+ tool,
58233
+ ...account === void 0 ? {} : { account },
58234
+ ...confirmToken === void 0 ? {} : { confirmToken },
58235
+ subject,
58236
+ ttlSeconds: confirmTtlFromEnv(env),
58237
+ instruction: mode === "auto" ? CONFIRM_TOKEN_AUTO_INSTRUCTION : instruction ?? CONFIRM_TOKEN_INSTRUCTION,
58238
+ ...spent === void 0 ? {} : { spent }
58239
+ }
58240
+ };
58241
+ }
58242
+
57768
58243
  // node_modules/@chrischall/mcp-utils/dist/server/index.js
57769
58244
  var SERVER_PROTOCOL_VERSIONS = Object.freeze([
57770
58245
  "2026-07-28",
@@ -57940,49 +58415,9 @@ function runMcp(opts) {
57940
58415
  return handle;
57941
58416
  }
57942
58417
 
57943
- // node_modules/@chrischall/mcp-utils/dist/config/index.js
57944
- import { homedir } from "node:os";
57945
- import { isAbsolute, join, resolve } from "node:path";
57946
- var PLACEHOLDER_RE = /^\$\{[^}]*\}$/;
57947
- function readEnvVar(key, opts = {}) {
57948
- const env = opts.env ?? process.env;
57949
- const raw = env[key];
57950
- if (typeof raw === "string") {
57951
- const trimmed = raw.trim();
57952
- if (trimmed.length > 0 && trimmed !== "undefined" && trimmed !== "null" && !PLACEHOLDER_RE.test(trimmed)) {
57953
- return trimmed;
57954
- }
57955
- }
57956
- return opts.default;
57957
- }
57958
- function expandPath(p) {
57959
- let expanded = p;
57960
- if (p === "~") {
57961
- expanded = homedir();
57962
- } else if (p.startsWith("~/")) {
57963
- expanded = join(homedir(), p.slice(2));
57964
- }
57965
- return isAbsolute(expanded) ? expanded : resolve(expanded);
57966
- }
57967
- async function loadDotenvSafely(opts = {}) {
57968
- try {
57969
- const mod = await import(
57970
- /* @vite-ignore */
57971
- "dotenv"
57972
- );
57973
- const result = mod.config({
57974
- ...opts.path !== void 0 ? { path: opts.path } : {},
57975
- override: opts.override ?? false,
57976
- quiet: true
57977
- });
57978
- return result.error === void 0;
57979
- } catch {
57980
- return false;
57981
- }
57982
- }
57983
-
57984
58418
  // node_modules/@chrischall/mcp-utils/dist/fs/index.js
57985
58419
  import { openAsBlob } from "node:fs";
58420
+ import { open as open2 } from "node:fs/promises";
57986
58421
 
57987
58422
  // node_modules/@chrischall/mcp-utils/dist/fs/confine.js
57988
58423
  import { existsSync, realpathSync } from "node:fs";
@@ -58019,6 +58454,24 @@ function assertPathWithinRoots(path, roots) {
58019
58454
  throw new Error(`Path is outside the allowed directories: ${path}`);
58020
58455
  }
58021
58456
 
58457
+ // node_modules/@chrischall/mcp-utils/dist/fs/output.js
58458
+ function sniffMimeBytes(bytes) {
58459
+ const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
58460
+ if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
58461
+ return "image/png";
58462
+ }
58463
+ if (buf.length >= 3 && buf[0] === 255 && buf[1] === 216 && buf[2] === 255) {
58464
+ return "image/jpeg";
58465
+ }
58466
+ if (buf.length >= 12 && buf.subarray(0, 4).toString("latin1") === "RIFF" && buf.subarray(8, 12).toString("latin1") === "WEBP") {
58467
+ return "image/webp";
58468
+ }
58469
+ if (buf.length >= 4 && buf.subarray(0, 4).toString("latin1") === "GIF8") {
58470
+ return "image/gif";
58471
+ }
58472
+ return void 0;
58473
+ }
58474
+
58022
58475
  // node_modules/@chrischall/mcp-utils/dist/fs/index.js
58023
58476
  async function fileBlob(path, opts = {}) {
58024
58477
  const target = opts.allowedRoots ? assertPathWithinRoots(path, opts.allowedRoots) : path;
@@ -58033,6 +58486,22 @@ async function fileBlob(path, opts = {}) {
58033
58486
  }
58034
58487
  return blob;
58035
58488
  }
58489
+ async function readFileHead(path, bytes, opts = {}) {
58490
+ const target = opts.allowedRoots ? assertPathWithinRoots(path, opts.allowedRoots) : path;
58491
+ let fh;
58492
+ try {
58493
+ fh = await open2(target, "r");
58494
+ } catch {
58495
+ throw new Error(`Cannot read file: ${path}`);
58496
+ }
58497
+ try {
58498
+ const buf = Buffer.alloc(bytes);
58499
+ const { bytesRead } = await fh.read(buf, 0, bytes, 0);
58500
+ return buf.subarray(0, bytesRead);
58501
+ } finally {
58502
+ await fh.close();
58503
+ }
58504
+ }
58036
58505
 
58037
58506
  // node_modules/@chrischall/mcp-utils/dist/http/index.js
58038
58507
  function buildQueryString(params) {
@@ -58091,7 +58560,7 @@ function toolAnnotations(opts = {}) {
58091
58560
  }
58092
58561
 
58093
58562
  // src/version.ts
58094
- var VERSION = "2.1.2";
58563
+ var VERSION = "2.2.0";
58095
58564
 
58096
58565
  // src/client.ts
58097
58566
  import { dirname as dirname2, join as join2 } from "path";
@@ -58598,7 +59067,9 @@ var SCHEMA_STATEMENTS = [
58598
59067
  beers_offset INTEGER,
58599
59068
  beers_total INTEGER,
58600
59069
  beers_complete INTEGER NOT NULL DEFAULT 0,
58601
- served_backfill_last INTEGER NOT NULL DEFAULT 0
59070
+ served_backfill_last INTEGER NOT NULL DEFAULT 0,
59071
+ beers_accepted_gap INTEGER NOT NULL DEFAULT 0,
59072
+ beers_rescan_target INTEGER
58602
59073
  )`
58603
59074
  ];
58604
59075
  var MIGRATIONS = [
@@ -58607,7 +59078,9 @@ var MIGRATIONS = [
58607
59078
  "ALTER TABLE sync_state ADD COLUMN beers_offset INTEGER",
58608
59079
  "ALTER TABLE sync_state ADD COLUMN beers_total INTEGER",
58609
59080
  "ALTER TABLE sync_state ADD COLUMN beers_complete INTEGER NOT NULL DEFAULT 0",
58610
- "ALTER TABLE sync_state ADD COLUMN served_backfill_last INTEGER NOT NULL DEFAULT 0"
59081
+ "ALTER TABLE sync_state ADD COLUMN served_backfill_last INTEGER NOT NULL DEFAULT 0",
59082
+ "ALTER TABLE sync_state ADD COLUMN beers_accepted_gap INTEGER NOT NULL DEFAULT 0",
59083
+ "ALTER TABLE sync_state ADD COLUMN beers_rescan_target INTEGER"
58611
59084
  ];
58612
59085
  var CheckinStoreCore = class {
58613
59086
  constructor(db) {
@@ -58729,7 +59202,9 @@ var CheckinStoreCore = class {
58729
59202
  beers_offset: num(row.beers_offset),
58730
59203
  beers_total: num(row.beers_total),
58731
59204
  beers_complete: Number(row.beers_complete) === 1,
58732
- served_backfill_last: Number(row.served_backfill_last) === 1
59205
+ served_backfill_last: Number(row.served_backfill_last) === 1,
59206
+ beers_accepted_gap: num(row.beers_accepted_gap) ?? 0,
59207
+ beers_rescan_target: num(row.beers_rescan_target)
58733
59208
  };
58734
59209
  }
58735
59210
  /**
@@ -58753,19 +59228,22 @@ var CheckinStoreCore = class {
58753
59228
  beers_offset: pick2("beers_offset", null),
58754
59229
  beers_total: pick2("beers_total", null),
58755
59230
  beers_complete: pick2("beers_complete", false),
58756
- served_backfill_last: pick2("served_backfill_last", false)
59231
+ served_backfill_last: pick2("served_backfill_last", false),
59232
+ beers_accepted_gap: pick2("beers_accepted_gap", 0),
59233
+ beers_rescan_target: pick2("beers_rescan_target", null)
58757
59234
  };
58758
59235
  this.db.run(
58759
59236
  `INSERT INTO sync_state
58760
- (username, oldest_max_id, newest_checkin_id, catchup_max_id, last_synced_at, backfill_complete, total_checkins, checkins_truncated, beers_offset, beers_total, beers_complete, served_backfill_last)
58761
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
59237
+ (username, oldest_max_id, newest_checkin_id, catchup_max_id, last_synced_at, backfill_complete, total_checkins, checkins_truncated, beers_offset, beers_total, beers_complete, served_backfill_last, beers_accepted_gap, beers_rescan_target)
59238
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
58762
59239
  ON CONFLICT(username) DO UPDATE SET
58763
59240
  oldest_max_id=excluded.oldest_max_id, newest_checkin_id=excluded.newest_checkin_id,
58764
59241
  catchup_max_id=excluded.catchup_max_id, last_synced_at=excluded.last_synced_at,
58765
59242
  backfill_complete=excluded.backfill_complete, total_checkins=excluded.total_checkins,
58766
59243
  checkins_truncated=excluded.checkins_truncated, beers_offset=excluded.beers_offset,
58767
59244
  beers_total=excluded.beers_total, beers_complete=excluded.beers_complete,
58768
- served_backfill_last=excluded.served_backfill_last`,
59245
+ served_backfill_last=excluded.served_backfill_last, beers_accepted_gap=excluded.beers_accepted_gap,
59246
+ beers_rescan_target=excluded.beers_rescan_target`,
58769
59247
  [
58770
59248
  key,
58771
59249
  next.oldest_max_id,
@@ -58778,7 +59256,9 @@ var CheckinStoreCore = class {
58778
59256
  next.beers_offset,
58779
59257
  next.beers_total,
58780
59258
  next.beers_complete ? 1 : 0,
58781
- next.served_backfill_last ? 1 : 0
59259
+ next.served_backfill_last ? 1 : 0,
59260
+ next.beers_accepted_gap,
59261
+ next.beers_rescan_target
58782
59262
  ]
58783
59263
  );
58784
59264
  }
@@ -59621,6 +60101,22 @@ function registerDiscoverTools(server, client2) {
59621
60101
  );
59622
60102
  }
59623
60103
 
60104
+ // src/tools/confirm.ts
60105
+ var CONFIRM_FLOW = "Asks the user to confirm first: a confirmation prompt where the client supports one; otherwise the first call returns a preview and a confirmToken, and only a repeat call with that token proceeds (see MCP_CONFIRM_MODE).";
60106
+ function confirmWrite(ctx, c) {
60107
+ return requireConfirmationWithFallback(
60108
+ ctx,
60109
+ confirmationFromEnv({
60110
+ action: c.action,
60111
+ message: c.message,
60112
+ details: c.preview,
60113
+ tool: c.tool,
60114
+ confirmToken: c.confirmToken,
60115
+ subject: () => ({ target: String(c.target), payload: c.payload, preview: c.preview })
60116
+ })
60117
+ );
60118
+ }
60119
+
59624
60120
  // src/tools/friends.ts
59625
60121
  var TargetUidSchema = external_exports.number().int().positive().describe("The target user id (uid) \u2014 from a user profile (response.user.uid) or a friends-list item");
59626
60122
  var ACTIONS = [
@@ -59659,7 +60155,7 @@ function registerFriendActionTools(server, client2) {
59659
60155
  action.tool,
59660
60156
  {
59661
60157
  title: action.title,
59662
- description: `${action.detail} Acts on YOUR account and affects a real relationship with another person. Without confirm: true it returns a dry-run preview and makes NO network call; with confirm: true it performs the action. Note: this endpoint path is taken from the Untappd app but is not otherwise independently verified.`,
60158
+ description: `${action.detail} Acts on YOUR account and affects a real relationship with another person. ${CONFIRM_FLOW} Note: this endpoint path is taken from the Untappd app but is not otherwise independently verified.`,
59663
60159
  // All four reach ANOTHER PERSON — the description says so itself: "affects
59664
60160
  // a real relationship with another person". A friend request cannot be
59665
60161
  // un-sent, and a rejection cannot be un-rejected, so none of them has an
@@ -59667,18 +60163,21 @@ function registerFriendActionTools(server, client2) {
59667
60163
  annotations: toolAnnotations({ title: action.title, readOnly: false, idempotent: true, openWorld: true, destructive: true }),
59668
60164
  inputSchema: external_exports.object({
59669
60165
  target_uid: TargetUidSchema,
59670
- confirm: schemaConfirm
60166
+ confirmToken: confirmTokenParam
59671
60167
  })
59672
60168
  },
59673
- async ({ target_uid, confirm }) => {
59674
- if (confirm !== true) {
59675
- return minifiedResult({
59676
- dryRun: true,
59677
- action: action.path,
59678
- target_uid,
59679
- note: `Dry run \u2014 re-run with confirm: true to ${action.verb} user ${target_uid}.`
59680
- });
59681
- }
60169
+ async ({ target_uid, confirmToken }, ctx) => {
60170
+ const request = { method: "POST", path: `/friend/${action.path}/${target_uid}` };
60171
+ const gate = await confirmWrite(ctx, {
60172
+ tool: action.tool,
60173
+ action: `untappd.friend_${action.path}`,
60174
+ message: `Review and confirm: ${action.verb} Untappd user ${target_uid}.`,
60175
+ confirmToken,
60176
+ target: target_uid,
60177
+ payload: request,
60178
+ preview: { action: action.path, target_uid, ...request, note: `Will ${action.verb} user ${target_uid}.` }
60179
+ });
60180
+ if (gate) return gate;
59682
60181
  const data = await client2.write("POST", `/friend/${action.path}/${target_uid}`);
59683
60182
  return minifiedResult({ done: true, action: action.path, target_uid, result: data?.result });
59684
60183
  }
@@ -59693,22 +60192,25 @@ function registerWishlistTools(server, client2) {
59693
60192
  "untappd_wishlist_add",
59694
60193
  {
59695
60194
  title: "Add a beer to your wishlist",
59696
- description: "Add a beer to YOUR Untappd wishlist by its bid. Without confirm: true it returns a dry-run preview and makes NO network call; with confirm: true it adds. Writes to your account.",
60195
+ description: `Add a beer to YOUR Untappd wishlist by its bid. Writes to your account. ${CONFIRM_FLOW}`,
59697
60196
  annotations: toolAnnotations({ title: "Add a beer to your wishlist", readOnly: false, idempotent: true, openWorld: true, destructive: false }),
59698
60197
  inputSchema: external_exports.object({
59699
60198
  bid: BidSchema2,
59700
- confirm: schemaConfirm
60199
+ confirmToken: confirmTokenParam
59701
60200
  })
59702
60201
  },
59703
- async ({ bid, confirm }) => {
59704
- if (confirm !== true) {
59705
- return minifiedResult({
59706
- dryRun: true,
59707
- action: "wishlist_add",
59708
- bid,
59709
- note: "Dry run \u2014 re-run with confirm: true to add this beer to your wishlist."
59710
- });
59711
- }
60202
+ async ({ bid, confirmToken }, ctx) => {
60203
+ const request = { method: "GET", path: "/user/wishlist/add", query: { bid } };
60204
+ const gate = await confirmWrite(ctx, {
60205
+ tool: "untappd_wishlist_add",
60206
+ action: "untappd.wishlist_add",
60207
+ message: "Review and confirm adding this beer to your Untappd wishlist:",
60208
+ confirmToken,
60209
+ target: bid,
60210
+ payload: request,
60211
+ preview: { action: "wishlist_add", bid, ...request, note: "Adds this beer to your Untappd wishlist." }
60212
+ });
60213
+ if (gate) return gate;
59712
60214
  const data = await client2.write("GET", "/user/wishlist/add", { query: { bid } });
59713
60215
  return minifiedResult({ added: true, bid, result: data?.result });
59714
60216
  }
@@ -59717,22 +60219,25 @@ function registerWishlistTools(server, client2) {
59717
60219
  "untappd_wishlist_remove",
59718
60220
  {
59719
60221
  title: "Remove a beer from your wishlist",
59720
- description: "Remove a beer from YOUR Untappd wishlist by its bid. Without confirm: true it returns a dry-run preview and makes NO network call; with confirm: true it removes. Writes to your account.",
60222
+ description: `Remove a beer from YOUR Untappd wishlist by its bid. Writes to your account. ${CONFIRM_FLOW}`,
59721
60223
  annotations: toolAnnotations({ title: "Remove a beer from your wishlist", readOnly: false, idempotent: true, openWorld: true, destructive: false }),
59722
60224
  inputSchema: external_exports.object({
59723
60225
  bid: BidSchema2,
59724
- confirm: schemaConfirm
60226
+ confirmToken: confirmTokenParam
59725
60227
  })
59726
60228
  },
59727
- async ({ bid, confirm }) => {
59728
- if (confirm !== true) {
59729
- return minifiedResult({
59730
- dryRun: true,
59731
- action: "wishlist_remove",
59732
- bid,
59733
- note: "Dry run \u2014 re-run with confirm: true to remove this beer from your wishlist."
59734
- });
59735
- }
60229
+ async ({ bid, confirmToken }, ctx) => {
60230
+ const request = { method: "GET", path: "/user/wishlist/delete", query: { bid } };
60231
+ const gate = await confirmWrite(ctx, {
60232
+ tool: "untappd_wishlist_remove",
60233
+ action: "untappd.wishlist_remove",
60234
+ message: "Review and confirm removing this beer from your Untappd wishlist:",
60235
+ confirmToken,
60236
+ target: bid,
60237
+ payload: request,
60238
+ preview: { action: "wishlist_remove", bid, ...request, note: "Removes this beer from your Untappd wishlist." }
60239
+ });
60240
+ if (gate) return gate;
59736
60241
  const data = await client2.write("GET", "/user/wishlist/delete", { query: { bid } });
59737
60242
  return minifiedResult({ removed: true, bid, result: data?.result });
59738
60243
  }
@@ -59740,42 +60245,149 @@ function registerWishlistTools(server, client2) {
59740
60245
  }
59741
60246
 
59742
60247
  // src/tools/checkin.ts
59743
- import { existsSync as existsSync2 } from "node:fs";
59744
- import { extname } from "node:path";
60248
+ import { createReadStream, realpathSync as realpathSync2, statSync } from "node:fs";
60249
+ import { createHash as createHash4 } from "node:crypto";
60250
+ import { pipeline } from "node:stream/promises";
60251
+ import { delimiter, extname } from "node:path";
59745
60252
  var CheckinIdSchema = external_exports.number().int().positive().describe("Untappd check-in id");
59746
60253
  var PHOTO_CONTENT_TYPES = { jpg: "image/jpeg", png: "image/png" };
59747
60254
  function photoExt(path) {
59748
60255
  const ext = extname(path).slice(1).toLowerCase();
59749
60256
  return ext === "jpeg" ? "jpg" : ext;
59750
60257
  }
60258
+ var MAX_PHOTO_BYTES = 15 * 1024 * 1024;
60259
+ function photoRoots() {
60260
+ const raw = readEnvVar("UNTAPPD_PHOTO_DIR");
60261
+ const roots = raw?.split(delimiter).filter(Boolean);
60262
+ return roots && roots.length > 0 ? roots : void 0;
60263
+ }
60264
+ async function checkPhoto(photoPath) {
60265
+ const ext = photoExt(photoPath);
60266
+ if (!(ext in PHOTO_CONTENT_TYPES)) {
60267
+ throw createHelpfulError(`Unsupported photo type "${ext || "(none)"}".`, {
60268
+ hint: "Attach a .jpg, .jpeg, or .png file."
60269
+ });
60270
+ }
60271
+ const roots = photoRoots();
60272
+ if (roots) {
60273
+ try {
60274
+ assertPathWithinRoots(photoPath, roots);
60275
+ } catch {
60276
+ throw createHelpfulError("The photo is outside the allowed photo directory.", {
60277
+ hint: "UNTAPPD_PHOTO_DIR restricts which files can be attached to a check-in."
60278
+ });
60279
+ }
60280
+ }
60281
+ let real;
60282
+ let size;
60283
+ try {
60284
+ real = realpathSync2(photoPath);
60285
+ const st = statSync(real);
60286
+ if (!st.isFile()) throw new Error("not a file");
60287
+ size = st.size;
60288
+ } catch {
60289
+ throw new McpToolError("Photo file not found or not readable.");
60290
+ }
60291
+ if (size > MAX_PHOTO_BYTES) {
60292
+ throw createHelpfulError(`Photo is too large (${size} bytes; the limit is ${MAX_PHOTO_BYTES}).`, {
60293
+ hint: "Attach a normal-sized JPEG or PNG photo."
60294
+ });
60295
+ }
60296
+ const sniffed = sniffMimeBytes(await readFileHead(real, 16));
60297
+ if (sniffed !== PHOTO_CONTENT_TYPES[ext]) {
60298
+ throw createHelpfulError(
60299
+ sniffed === "image/jpeg" || sniffed === "image/png" ? `Photo content (${sniffed}) does not match its .${ext} extension.` : "The file is not a JPEG or PNG image.",
60300
+ { hint: "Attach a real .jpg/.jpeg or .png photo." }
60301
+ );
60302
+ }
60303
+ return { path: real, size_bytes: size, ext, content_type: sniffed };
60304
+ }
60305
+ async function photoSha256(path) {
60306
+ const hash2 = createHash4("sha256");
60307
+ await pipeline(createReadStream(path), hash2);
60308
+ return hash2.digest("hex");
60309
+ }
59751
60310
  var RatingSchema = external_exports.number().min(0).max(5).refine((r) => Math.round(r * 4) === r * 4, { message: "rating must be a multiple of 0.25" });
59752
- function localTimezone() {
59753
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
59754
- const gmt_offset = -(/* @__PURE__ */ new Date()).getTimezoneOffset() / 60;
59755
- return { timezone, gmt_offset };
60311
+ function gmtOffsetHours(timeZone, at) {
60312
+ const name = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" }).formatToParts(at).find((p) => p.type === "timeZoneName")?.value;
60313
+ const m = /GMT([+-])(\d{1,2})(?::(\d{2}))?/.exec(name ?? "");
60314
+ if (!m) return 0;
60315
+ const hours = Number(m[2]) + Number(m[3] ?? 0) / 60;
60316
+ return m[1] === "-" ? -hours : hours;
60317
+ }
60318
+ function checkinTimezone(requested) {
60319
+ const timezone = requested ?? readEnvVar("UNTAPPD_TIMEZONE") ?? (Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC");
60320
+ try {
60321
+ return { timezone, gmt_offset: gmtOffsetHours(timezone, /* @__PURE__ */ new Date()) };
60322
+ } catch {
60323
+ throw createHelpfulError(`Unknown timezone "${timezone}".`, {
60324
+ hint: 'Pass an IANA timezone name such as "America/New_York" or "Europe/London".'
60325
+ });
60326
+ }
60327
+ }
60328
+ var RECOVERY_WINDOW_MS = 3e4;
60329
+ async function nonIdempotentWrite(run, unknownOutcome) {
60330
+ try {
60331
+ return await run();
60332
+ } catch (e) {
60333
+ if (e instanceof UnreachableError) throw new McpToolError(unknownOutcome);
60334
+ throw e;
60335
+ }
60336
+ }
60337
+ async function findRecentCheckin(client2, bid, sentAt) {
60338
+ const self = client2.loginName;
60339
+ if (!self) return null;
60340
+ try {
60341
+ const data = await client2.get(
60342
+ `/user/checkins/${encodeURIComponent(self)}`,
60343
+ { limit: 5 }
60344
+ );
60345
+ const matches = [];
60346
+ for (const it of data?.checkins?.items ?? []) {
60347
+ const c = it;
60348
+ const at = Date.parse(c.created_at ?? "");
60349
+ if (c.beer?.bid === bid && typeof c.checkin_id === "number" && at >= sentAt - RECOVERY_WINDOW_MS) {
60350
+ matches.push(c.checkin_id);
60351
+ }
60352
+ }
60353
+ if (matches.length === 1) return matches[0];
60354
+ } catch {
60355
+ }
60356
+ return null;
59756
60357
  }
59757
60358
  function registerCheckinTools(server, client2) {
59758
60359
  server.registerTool(
59759
60360
  "untappd_toast",
59760
60361
  {
59761
60362
  title: "Toast an Untappd check-in",
59762
- description: "Toast (like) a check-in on YOUR account. This endpoint is a TOGGLE: calling it on a check-in you have already toasted removes the toast. Without confirm: true it returns a dry-run preview and makes NO network call; with confirm: true it posts. Writes to your Untappd account and is visible to others.",
60363
+ description: `Toast (like) a check-in on YOUR account. This endpoint is a TOGGLE: calling it on a check-in you have already toasted removes the toast. Writes to your Untappd account and is visible to others. ${CONFIRM_FLOW}`,
59763
60364
  annotations: toolAnnotations({ title: "Toast an Untappd check-in", readOnly: false, idempotent: false, openWorld: true, destructive: false }),
59764
60365
  inputSchema: external_exports.object({
59765
60366
  checkin_id: CheckinIdSchema,
59766
- confirm: schemaConfirm
60367
+ confirmToken: confirmTokenParam
59767
60368
  })
59768
60369
  },
59769
- async ({ checkin_id, confirm }) => {
59770
- if (confirm !== true) {
59771
- return minifiedResult({
59772
- dryRun: true,
60370
+ async ({ checkin_id, confirmToken }, ctx) => {
60371
+ const request = { method: "POST", path: `/checkin/toast/${checkin_id}` };
60372
+ const gate = await confirmWrite(ctx, {
60373
+ tool: "untappd_toast",
60374
+ action: "untappd.toast",
60375
+ message: "Review and confirm toggling your toast on this Untappd check-in:",
60376
+ confirmToken,
60377
+ target: checkin_id,
60378
+ payload: request,
60379
+ preview: {
59773
60380
  action: "toast",
59774
60381
  checkin_id,
59775
- note: "Dry run \u2014 re-run with confirm: true to toggle your toast on this check-in."
59776
- });
59777
- }
59778
- const data = await client2.write("POST", `/checkin/toast/${checkin_id}`);
60382
+ ...request,
60383
+ note: "Toggles your toast on this check-in (removes it if you have already toasted)."
60384
+ }
60385
+ });
60386
+ if (gate) return gate;
60387
+ const data = await nonIdempotentWrite(
60388
+ () => client2.write("POST", `/checkin/toast/${checkin_id}`),
60389
+ `Untappd did not answer the toast request for check-in ${checkin_id} in time, so it may or may not have been applied. Toast is a TOGGLE: retrying could remove a toast that did land. Check with untappd_checkin_info (checkin_id ${checkin_id}) before retrying.`
60390
+ );
59779
60391
  return minifiedResult({ toggled: true, checkin_id, result: data?.result, like_type: data?.like_type });
59780
60392
  }
59781
60393
  );
@@ -59783,25 +60395,36 @@ function registerCheckinTools(server, client2) {
59783
60395
  "untappd_add_comment",
59784
60396
  {
59785
60397
  title: "Comment on an Untappd check-in",
59786
- description: "Post a comment on a check-in from YOUR account. Without confirm: true it returns a dry-run preview and makes NO network call; with confirm: true it posts. Writes to your Untappd account and is visible to others.",
60398
+ description: "Post a comment on a check-in from YOUR account. Writes to your Untappd account and is visible to others. " + CONFIRM_FLOW,
59787
60399
  annotations: toolAnnotations({ title: "Comment on an Untappd check-in", readOnly: false, idempotent: false, openWorld: true, destructive: false }),
59788
60400
  inputSchema: external_exports.object({
59789
60401
  checkin_id: CheckinIdSchema,
59790
60402
  comment: external_exports.string().min(1).max(2e3).describe("Comment text to post"),
59791
- confirm: schemaConfirm
60403
+ confirmToken: confirmTokenParam
59792
60404
  })
59793
60405
  },
59794
- async ({ checkin_id, comment, confirm }) => {
59795
- if (confirm !== true) {
59796
- return minifiedResult({
59797
- dryRun: true,
60406
+ async ({ checkin_id, comment, confirmToken }, ctx) => {
60407
+ const request = { method: "POST", path: `/checkin/addcomment/${checkin_id}`, form: { comment } };
60408
+ const gate = await confirmWrite(ctx, {
60409
+ tool: "untappd_add_comment",
60410
+ action: "untappd.add_comment",
60411
+ message: "Review and confirm posting this comment from your Untappd account:",
60412
+ confirmToken,
60413
+ target: checkin_id,
60414
+ payload: request,
60415
+ preview: {
59798
60416
  action: "add_comment",
59799
60417
  checkin_id,
59800
60418
  comment,
59801
- note: "Dry run \u2014 re-run with confirm: true to post this comment to your Untappd account."
59802
- });
59803
- }
59804
- const data = await client2.write("POST", `/checkin/addcomment/${checkin_id}`, { form: { comment } });
60419
+ ...request,
60420
+ note: "Posts this comment to the check-in from your Untappd account, visible to others."
60421
+ }
60422
+ });
60423
+ if (gate) return gate;
60424
+ const data = await nonIdempotentWrite(
60425
+ () => client2.write("POST", `/checkin/addcomment/${checkin_id}`, { form: { comment } }),
60426
+ `Untappd did not answer in time, so the comment may have been posted already. Check the comments with untappd_checkin_info (checkin_id ${checkin_id}) before retrying, or it may be posted twice.`
60427
+ );
59805
60428
  return minifiedResult({ posted: true, checkin_id, response: data });
59806
60429
  }
59807
60430
  );
@@ -59809,22 +60432,25 @@ function registerCheckinTools(server, client2) {
59809
60432
  "untappd_delete_comment",
59810
60433
  {
59811
60434
  title: "Delete a comment from an Untappd check-in",
59812
- description: "Delete one of YOUR comments by its comment id (the id from a check-in's comments list). Without confirm: true it returns a dry-run preview and makes NO network call; with confirm: true it deletes.",
60435
+ description: `Delete one of YOUR comments by its comment id (the id from a check-in's comments list). ${CONFIRM_FLOW}`,
59813
60436
  annotations: toolAnnotations({ title: "Delete a comment from an Untappd check-in", readOnly: false, idempotent: true, openWorld: true, destructive: true }),
59814
60437
  inputSchema: external_exports.object({
59815
60438
  comment_id: external_exports.number().int().positive().describe("Untappd comment id (from a check-in's comments.items)"),
59816
- confirm: schemaConfirm
60439
+ confirmToken: confirmTokenParam
59817
60440
  })
59818
60441
  },
59819
- async ({ comment_id, confirm }) => {
59820
- if (confirm !== true) {
59821
- return minifiedResult({
59822
- dryRun: true,
59823
- action: "delete_comment",
59824
- comment_id,
59825
- note: "Dry run \u2014 re-run with confirm: true to delete this comment from your Untappd account."
59826
- });
59827
- }
60442
+ async ({ comment_id, confirmToken }, ctx) => {
60443
+ const request = { method: "POST", path: `/checkin/deletecomment/${comment_id}` };
60444
+ const gate = await confirmWrite(ctx, {
60445
+ tool: "untappd_delete_comment",
60446
+ action: "untappd.delete_comment",
60447
+ message: "Review and confirm deleting this comment from your Untappd account:",
60448
+ confirmToken,
60449
+ target: comment_id,
60450
+ payload: request,
60451
+ preview: { action: "delete_comment", comment_id, ...request, note: "Deletes this comment from your Untappd account." }
60452
+ });
60453
+ if (gate) return gate;
59828
60454
  const data = await client2.write("POST", `/checkin/deletecomment/${comment_id}`);
59829
60455
  return minifiedResult({ deleted: true, comment_id, result: data?.result });
59830
60456
  }
@@ -59833,22 +60459,30 @@ function registerCheckinTools(server, client2) {
59833
60459
  "untappd_delete_checkin",
59834
60460
  {
59835
60461
  title: "Delete an Untappd check-in",
59836
- description: "Permanently delete one of YOUR check-ins by its id. This is destructive and cannot be undone. Without confirm: true it returns a dry-run preview and makes NO network call; with confirm: true it deletes.",
60462
+ description: `Permanently delete one of YOUR check-ins by its id. This is destructive and cannot be undone. ${CONFIRM_FLOW}`,
59837
60463
  annotations: toolAnnotations({ title: "Delete an Untappd check-in", readOnly: false, idempotent: true, openWorld: true, destructive: true }),
59838
60464
  inputSchema: external_exports.object({
59839
60465
  checkin_id: CheckinIdSchema,
59840
- confirm: schemaConfirm
60466
+ confirmToken: confirmTokenParam
59841
60467
  })
59842
60468
  },
59843
- async ({ checkin_id, confirm }) => {
59844
- if (confirm !== true) {
59845
- return minifiedResult({
59846
- dryRun: true,
60469
+ async ({ checkin_id, confirmToken }, ctx) => {
60470
+ const request = { method: "POST", path: `/checkin/delete/${checkin_id}` };
60471
+ const gate = await confirmWrite(ctx, {
60472
+ tool: "untappd_delete_checkin",
60473
+ action: "untappd.delete_checkin",
60474
+ message: "Review and confirm PERMANENTLY deleting this Untappd check-in:",
60475
+ confirmToken,
60476
+ target: checkin_id,
60477
+ payload: request,
60478
+ preview: {
59847
60479
  action: "delete_checkin",
59848
60480
  checkin_id,
59849
- note: "Dry run \u2014 re-run with confirm: true to PERMANENTLY delete this check-in. This cannot be undone."
59850
- });
59851
- }
60481
+ ...request,
60482
+ note: "PERMANENTLY deletes this check-in. This cannot be undone."
60483
+ }
60484
+ });
60485
+ if (gate) return gate;
59852
60486
  const data = await client2.write("POST", `/checkin/delete/${checkin_id}`);
59853
60487
  return minifiedResult({ deleted: true, checkin_id, result: data?.result });
59854
60488
  }
@@ -59857,31 +60491,29 @@ function registerCheckinTools(server, client2) {
59857
60491
  "untappd_checkin",
59858
60492
  {
59859
60493
  title: "Check in a beer on Untappd",
59860
- description: "Post a NEW beer check-in to YOUR Untappd account \u2014 this publishes to your public feed. Provide the beer id (bid) from untappd_search_beer; optionally a rating (0\u20135 in 0.25 steps), a shout (comment), a venue via foursquare_id, and a local photo via photo_path (JPEG/PNG). Without confirm: true it returns a dry-run preview of the exact fields and makes NO network call; with confirm: true it posts.",
60494
+ description: `Post a NEW beer check-in to YOUR Untappd account \u2014 this publishes to your public feed. Provide the beer id (bid) from untappd_search_beer; optionally a rating (0\u20135 in 0.25 steps), a shout (comment), a venue via foursquare_id, and a local photo via photo_path (JPEG/PNG). The preview shows the exact fields and photo that will be posted. ${CONFIRM_FLOW}`,
59861
60495
  annotations: toolAnnotations({ title: "Check in a beer on Untappd", readOnly: false, idempotent: false, openWorld: true, destructive: false }),
59862
60496
  inputSchema: external_exports.object({
59863
60497
  bid: external_exports.number().int().positive().describe("Untappd beer id to check in (from untappd_search_beer)"),
59864
60498
  rating: RatingSchema.optional().describe("Rating 0\u20135 in 0.25 increments (omit for no rating)"),
59865
60499
  shout: external_exports.string().max(2e3).optional().describe("Optional shout / comment text for the check-in"),
59866
60500
  foursquare_id: external_exports.string().optional().describe("Optional Foursquare venue id to tag the check-in location"),
59867
- photo_path: external_exports.string().optional().describe("Optional path to a local JPEG/PNG photo to attach to the check-in"),
60501
+ photo_path: external_exports.string().optional().describe(
60502
+ "Optional path to a local JPEG/PNG photo (max 15 MB) to attach \u2014 it is published publicly. Only use a file the user explicitly chose; the preview shows the resolved path and size for them to confirm."
60503
+ ),
59868
60504
  geolat: external_exports.number().optional().describe("Optional latitude of the check-in"),
59869
60505
  geolng: external_exports.number().optional().describe("Optional longitude of the check-in"),
59870
60506
  container_id: external_exports.number().int().optional().describe("Optional serving container id (e.g. 1 = draft, 2 = bottle, 3 = can)"),
59871
- confirm: schemaConfirm
60507
+ timezone: external_exports.string().min(1).optional().describe(
60508
+ "The drinker's IANA timezone (e.g. America/New_York), which sets the check-in's local time. Defaults to UNTAPPD_TIMEZONE, else the server's own zone \u2014 which on a hosted connector is usually UTC, so pass it when you know where the user is."
60509
+ ),
60510
+ confirmToken: confirmTokenParam
59872
60511
  })
59873
60512
  },
59874
- async ({ bid, rating, shout, foursquare_id, photo_path, geolat, geolng, container_id, confirm }) => {
59875
- const { timezone, gmt_offset } = localTimezone();
59876
- let ext;
59877
- if (photo_path !== void 0) {
59878
- ext = photoExt(photo_path);
59879
- if (!(ext in PHOTO_CONTENT_TYPES)) {
59880
- throw createHelpfulError(`Unsupported photo type "${ext || "(none)"}".`, {
59881
- hint: "Attach a .jpg, .jpeg, or .png file."
59882
- });
59883
- }
59884
- }
60513
+ async ({ bid, rating, shout, foursquare_id, photo_path, geolat, geolng, container_id, timezone: requestedTz, confirmToken }, ctx) => {
60514
+ const { timezone, gmt_offset } = checkinTimezone(requestedTz);
60515
+ const photo = photo_path !== void 0 ? await checkPhoto(photo_path) : void 0;
60516
+ const photo_sha256 = photo ? await photoSha256(photo.path) : void 0;
59885
60517
  const form = {
59886
60518
  bid,
59887
60519
  rating: rating !== void 0 ? rating.toFixed(2) : void 0,
@@ -59892,31 +60524,57 @@ function registerCheckinTools(server, client2) {
59892
60524
  container_id,
59893
60525
  timezone,
59894
60526
  gmt_offset,
59895
- is_photo: photo_path !== void 0 ? "true" : "false",
59896
- photo_file_ext: photo_path !== void 0 ? ext : void 0,
60527
+ is_photo: photo ? "true" : "false",
60528
+ photo_file_ext: photo?.ext,
59897
60529
  platform: "ios"
59898
60530
  };
59899
- if (confirm !== true) {
59900
- return minifiedResult({
59901
- dryRun: true,
60531
+ const request = { method: "POST", path: "/checkin/add", form };
60532
+ const gate = await confirmWrite(ctx, {
60533
+ tool: "untappd_checkin",
60534
+ action: "untappd.checkin",
60535
+ message: "Review and confirm posting this check-in to your public Untappd feed:",
60536
+ confirmToken,
60537
+ target: bid,
60538
+ payload: { ...request, photo, photo_sha256 },
60539
+ preview: {
59902
60540
  action: "checkin",
59903
- form,
59904
- photo: photo_path !== void 0 ? { path: photo_path, note: "will be uploaded after the check-in is created" } : void 0,
59905
- note: "Dry run \u2014 re-run with confirm: true to POST this check-in to your public Untappd feed."
59906
- });
59907
- }
60541
+ ...request,
60542
+ photo: photo ? { ...photo, note: "this exact file will be uploaded PUBLICLY after the check-in is created" } : void 0,
60543
+ note: "POSTs this check-in to your public Untappd feed."
60544
+ }
60545
+ });
60546
+ if (gate) return gate;
59908
60547
  let blob;
59909
- if (photo_path !== void 0) {
59910
- if (!existsSync2(photo_path)) throw new McpToolError(`Photo file not found: ${photo_path}`);
59911
- blob = await fileBlob(photo_path);
60548
+ if (photo) {
60549
+ blob = await fileBlob(photo.path, { maxBytes: MAX_PHOTO_BYTES, label: "Photo", allowedRoots: photoRoots() });
60550
+ }
60551
+ const sentAt = Date.now();
60552
+ let data;
60553
+ try {
60554
+ data = await client2.write("POST", "/checkin/add", { form });
60555
+ } catch (e) {
60556
+ if (!(e instanceof UnreachableError)) throw e;
60557
+ const found = await findRecentCheckin(client2, bid, sentAt);
60558
+ if (found === null) {
60559
+ throw new McpToolError(
60560
+ "Untappd did not answer the check-in request in time, so the check-in may have been created anyway (it could not be confirmed either way). Look at your latest check-ins with untappd_user_checkins before retrying \u2014 retrying a check-in that did land posts it twice."
60561
+ );
60562
+ }
60563
+ return minifiedResult({
60564
+ checked_in: true,
60565
+ checkin_id: found,
60566
+ recovered: true,
60567
+ photo_attached: false,
60568
+ ...photo ? { photo_error: `Check-in ${found} was created, but its photo upload URL was lost with the timed-out response, so no photo was attached.` } : {},
60569
+ note: "Untappd did not answer in time, but the check-in was found on your account \u2014 it was created. Do not retry."
60570
+ });
59912
60571
  }
59913
- const data = await client2.write("POST", "/checkin/add", { form });
59914
60572
  let photo_attached = false;
59915
60573
  let photo_error;
59916
- if (photo_path !== void 0) {
60574
+ if (photo) {
59917
60575
  if (data?.photo_upload?.url && data.checkin_id) {
59918
60576
  try {
59919
- await client2.putBinary(data.photo_upload.url, blob, PHOTO_CONTENT_TYPES[ext]);
60577
+ await client2.putBinary(data.photo_upload.url, blob, photo.content_type);
59920
60578
  await client2.write("POST", "/photo/uploadComplete", {
59921
60579
  form: { checkin_id: data.checkin_id, destination_url: data.photo_upload.destination_url }
59922
60580
  });
@@ -60226,6 +60884,7 @@ async function syncCheckins(client2, cache, rawUsername, options = {}) {
60226
60884
 
60227
60885
  // src/cache/sync-beers.ts
60228
60886
  var PAGE_LIMIT2 = 50;
60887
+ var RESUME_OVERLAP = 10;
60229
60888
  async function fetchBeersPage(client2, encodedUser, offset) {
60230
60889
  const data = await client2.get(
60231
60890
  `/user/beers/${encodedUser}`,
@@ -60248,8 +60907,11 @@ async function syncUserBeers(client2, cache, rawUsername, maxPages = 10) {
60248
60907
  const now = () => (/* @__PURE__ */ new Date()).toISOString();
60249
60908
  const prior = await cache.getState(rawUsername);
60250
60909
  const incremental = (prior?.beers_complete ?? false) && !!prior?.last_synced_at;
60251
- let offset = incremental ? 0 : prior?.beers_offset ?? 0;
60910
+ let refreshing = incremental;
60911
+ let offset = incremental ? 0 : Math.max(0, (prior?.beers_offset ?? 0) - RESUME_OVERLAP);
60252
60912
  let total = prior?.beers_total ?? null;
60913
+ let acceptedGap = prior?.beers_accepted_gap ?? 0;
60914
+ let rescanTarget = incremental ? null : prior?.beers_rescan_target ?? null;
60253
60915
  let complete = false;
60254
60916
  let pages = 0;
60255
60917
  let added = 0;
@@ -60263,31 +60925,41 @@ async function syncUserBeers(client2, cache, rawUsername, maxPages = 10) {
60263
60925
  });
60264
60926
  }
60265
60927
  };
60928
+ const gapNow = async () => total === null ? 0 : total - await cache.distinctBeersCount(rawUsername);
60266
60929
  for (; pages < maxPages && !complete; ) {
60267
60930
  const page = pages === 0 ? await firstFetch(offset) : await fetchBeersPage(client2, encodedUser, offset);
60268
60931
  pages++;
60269
60932
  if (page.total !== null) total = page.total;
60270
- if (page.items.length === 0) {
60271
- complete = true;
60272
- await cache.setState(rawUsername, {
60273
- beers_offset: incremental ? total ?? offset : offset,
60274
- beers_total: total,
60275
- beers_complete: true,
60276
- last_synced_at: now()
60277
- });
60278
- break;
60933
+ let atEnd = page.items.length === 0;
60934
+ if (!atEnd) {
60935
+ const rows = rowsOf2(rawUsername, page.items);
60936
+ const netNew = await cache.upsertDistinctBeers(rawUsername, rows);
60937
+ added += netNew;
60938
+ offset += page.items.length;
60939
+ if (total !== null && offset >= total) atEnd = true;
60940
+ else if (page.items.length < PAGE_LIMIT2) atEnd = true;
60941
+ else if (refreshing && netNew === 0) atEnd = true;
60942
+ else if (rescanTarget !== null && await gapNow() <= rescanTarget) atEnd = true;
60943
+ }
60944
+ if (atEnd) {
60945
+ const gap = await gapNow();
60946
+ if (gap > acceptedGap && rescanTarget === null) {
60947
+ rescanTarget = acceptedGap;
60948
+ acceptedGap = gap;
60949
+ refreshing = false;
60950
+ offset = 0;
60951
+ } else {
60952
+ complete = true;
60953
+ rescanTarget = null;
60954
+ acceptedGap = Math.max(0, gap);
60955
+ }
60279
60956
  }
60280
- const rows = rowsOf2(rawUsername, page.items);
60281
- const netNew = await cache.upsertDistinctBeers(rawUsername, rows);
60282
- added += netNew;
60283
- offset += page.items.length;
60284
- if (total !== null && offset >= total) complete = true;
60285
- else if (page.items.length < PAGE_LIMIT2) complete = true;
60286
- else if (incremental && netNew === 0) complete = true;
60287
60957
  await cache.setState(rawUsername, {
60288
- beers_offset: incremental ? total ?? offset : offset,
60958
+ beers_offset: refreshing ? total ?? offset : offset,
60289
60959
  beers_total: total,
60290
60960
  beers_complete: complete,
60961
+ beers_accepted_gap: acceptedGap,
60962
+ beers_rescan_target: rescanTarget,
60291
60963
  last_synced_at: now()
60292
60964
  });
60293
60965
  }