@notifkit/mcp 0.1.6 → 0.1.8

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.
@@ -12,6 +12,10 @@ interface ToolResult {
12
12
  /** Wrap a handler so a failed request is reported to the model instead of killing the server. */
13
13
  export declare function handler<T>(fn: (args: T) => Promise<unknown>): (args: T) => Promise<ToolResult>;
14
14
  export type EscapeMode = "html" | "header" | "text";
15
+ /** The value at a dotted path, reading own properties only; undefined when missing. */
16
+ export declare function valueAt(variables: Record<string, unknown>, path: string): unknown;
17
+ /** Every placeholder path used in the strings of a content tree, once each, in order. */
18
+ export declare function placeholderPaths(node: unknown): string[];
15
19
  export declare function renderContentNode(node: unknown, variables: Record<string, unknown>, mode: EscapeMode): unknown;
16
20
  export {};
17
21
  //# sourceMappingURL=shared.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/tools/shared.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,QAAQ,oGAUX,CAAC;AAEX,eAAO,MAAM,gBAAgB,oGAAW,CAAC;AACzC,eAAO,MAAM,UAAU,gDAAiD,CAAC;AAEzE,UAAU,UAAU;IAGlB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC1C,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAuBD,iGAAiG;AACjG,wBAAgB,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,IAC5C,MAAM,CAAC,KAAG,OAAO,CAAC,UAAU,CAAC,CAO5C;AAiBD,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,MAAM,CAAC;AAyCpD,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,EACb,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,IAAI,EAAE,UAAU,GACf,OAAO,CAWT"}
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/tools/shared.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,QAAQ,oGAUX,CAAC;AAEX,eAAO,MAAM,gBAAgB,oGAAW,CAAC;AACzC,eAAO,MAAM,UAAU,gDAAiD,CAAC;AAEzE,UAAU,UAAU;IAGlB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC1C,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAuBD,iGAAiG;AACjG,wBAAgB,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,IAC5C,MAAM,CAAC,KAAG,OAAO,CAAC,UAAU,CAAC,CAO5C;AAiBD,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,MAAM,CAAC;AA0BpD,uFAAuF;AACvF,wBAAgB,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CASjF;AA6BD,yFAAyF;AACzF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,EAAE,CAaxD;AAED,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,EACb,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,IAAI,EAAE,UAAU,GACf,OAAO,CAWT"}
@@ -73,25 +73,58 @@ function escapeModeFor(key, inherited) {
73
73
  return "header";
74
74
  return inherited;
75
75
  }
76
+ // Placeholders follow the server's renderer (src/templates/render.ts) so a
77
+ // preview shows what will be sent: `{{{path}}}` (group 1) or `{{path}}`
78
+ // (group 2), a path being a name or a dotted path (`user.name`), with optional
79
+ // whitespace inside the braces.
80
+ const PLACEHOLDER = /\{\{\{\s*(\w+(?:\.\w+)*)\s*\}\}\}|\{\{\s*(\w+(?:\.\w+)*)\s*\}\}/g;
81
+ /** The value at a dotted path, reading own properties only; undefined when missing. */
82
+ export function valueAt(variables, path) {
83
+ let value = variables;
84
+ for (const segment of path.split(".")) {
85
+ if (value === null || typeof value !== "object" || !Object.hasOwn(value, segment)) {
86
+ return undefined;
87
+ }
88
+ value = value[segment];
89
+ }
90
+ return value;
91
+ }
92
+ function lookup(variables, path) {
93
+ const value = valueAt(variables, path);
94
+ if (value === undefined || value === null)
95
+ return "";
96
+ return typeof value === "string" ? value : JSON.stringify(value);
97
+ }
98
+ function applyEscape(value, mode) {
99
+ if (mode === "html")
100
+ return escapeHtml(value);
101
+ if (mode === "header")
102
+ return escapeHeader(value);
103
+ return value;
104
+ }
105
+ // One pass, so an inserted value is never scanned for placeholders again.
76
106
  function interpolateValue(tmpl, variables, mode) {
77
- return tmpl
78
- .replace(/\{\{\{(\w+)\}\}\}/g, (_, k) => {
79
- const raw = variables[k];
80
- if (raw === undefined || raw === null)
81
- return "";
82
- return typeof raw === "string" ? raw : JSON.stringify(raw);
83
- })
84
- .replace(/\{\{(\w+)\}\}/g, (_, k) => {
85
- const raw = variables[k];
86
- if (raw === undefined || raw === null)
87
- return "";
88
- const val = typeof raw === "string" ? raw : JSON.stringify(raw);
89
- if (mode === "html")
90
- return escapeHtml(val);
91
- if (mode === "header")
92
- return escapeHeader(val);
93
- return val;
94
- });
107
+ return tmpl.replace(PLACEHOLDER, (_, rawPath, escapedPath) => rawPath !== undefined
108
+ ? lookup(variables, rawPath)
109
+ : applyEscape(lookup(variables, escapedPath ?? ""), mode));
110
+ }
111
+ /** Every placeholder path used in the strings of a content tree, once each, in order. */
112
+ export function placeholderPaths(node) {
113
+ const paths = new Set();
114
+ const visit = (value) => {
115
+ if (typeof value === "string") {
116
+ for (const match of value.matchAll(PLACEHOLDER))
117
+ paths.add(match[1] ?? match[2] ?? "");
118
+ }
119
+ else if (Array.isArray(value)) {
120
+ value.forEach(visit);
121
+ }
122
+ else if (value && typeof value === "object") {
123
+ Object.values(value).forEach(visit);
124
+ }
125
+ };
126
+ visit(node);
127
+ return [...paths];
95
128
  }
96
129
  export function renderContentNode(node, variables, mode) {
97
130
  if (typeof node === "string")
@@ -1 +1 @@
1
- {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/tools/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,OAAO;IACP,KAAK;IACL,MAAM;IACN,SAAS;IACT,QAAQ;IACR,UAAU;IACV,SAAS;IACT,UAAU;IACV,OAAO;CACC,CAAC;AACX,iEAAiE;AACjE,MAAM,CAAC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AACzC,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAU,CAAC;AAUzE,8EAA8E;AAC9E,SAAS,EAAE,CAAC,KAAc;IACxB,MAAM,IAAI,GACR,KAAK,KAAK,SAAS;QACjB,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ;YACzB,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACvC,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAC/C,CAAC;AAED,SAAS,IAAI,CAAC,KAAc;IAC1B,MAAM,IAAI,GACR,KAAK,YAAY,gBAAgB;QAC/B,CAAC,CAAC,4BAA4B,KAAK,CAAC,MAAM,MAAM,KAAK,CAAC,O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Y,CAAC,GAAG,CAAC,CAAC;QAChD,OAAO,GAAG,CAAC;IACb,CAAC,CAAC,CAAC;AACP,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,IAAa,EACb,SAAkC,EAClC,IAAgB;IAEhB,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IAC7E,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,iBAAiB,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAC7F,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACrC,MAAM,GAAG,GAA4B,EAAE,CAAC;QACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAA+B,CAAC,EAAE,CAAC;YAC3E,GAAG,CAAC,GAAG,CAAC,GAAG,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;QAC3E,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { NotifkitApiError } from \"../client.js\";\n\nexport const CHANNELS = [\n \"email\",\n \"sms\",\n \"push\",\n \"webhook\",\n \"in-app\",\n \"telegram\",\n \"discord\",\n \"whatsapp\",\n \"slack\",\n] as const;\n// The server accepts contacts on every channel, in-app included.\nexport const CONTACT_CHANNELS = CHANNELS;\nexport const PRIORITIES = [\"low\", \"normal\", \"high\", \"critical\"] as const;\n\ninterface ToolResult {\n // The SDK's tool-result type carries an index signature for protocol\n // extensions; without one here an interface is not assignable to it.\n [key: string]: unknown;\n content: { type: \"text\"; text: string }[];\n isError?: boolean;\n}\n\n/** Render any handler return value as the text payload MCP clients expect. */\nfunction ok(value: unknown): ToolResult {\n const text =\n value === undefined\n ? \"Done.\"\n : typeof value === \"string\"\n ? value\n : JSON.stringify(value, null, 2);\n return { content: [{ type: \"text\", text }] };\n}\n\nfunction fail(error: unknown): ToolResult {\n const text =\n error instanceof NotifkitApiError\n ? `notifkit API error (HTTP ${error.status}): ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n/** Wrap a handler so a failed request is reported to the model instead of killing the server. */\nexport function handler<T>(fn: (args: T) => Promise<unknown>) {\n return async (args: T): Promise<ToolResult> => {\n try {\n return ok(await fn(args));\n } catch (error) {\n return fail(error);\n }\n };\n}\n\nfunction escapeHtml(unsafe: string): string {\n return String(unsafe)\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\nfunction escapeHeader(unsafe: string): string {\n return String(unsafe)\n .replace(/[\\r\\n]+/g, \" \")\n .trim();\n}\n\nexport type EscapeMode = \"html\" | \"header\" | \"text\";\nconst HTML_FIELDS = new Set([\"html\", \"htmlbody\", \"bodyhtml\", \"htmlcontent\"]);\nconst HEADER_FIELDS = new Set([\n \"subject\",\n \"title\",\n \"from\",\n \"replyto\",\n \"cc\",\n \"bcc\",\n \"preheader\",\n \"preview\",\n]);\n\nfunction escapeModeFor(key: string, inherited: EscapeMode): EscapeMode {\n const k = key.toLowerCase().replace(/[-_]/g, \"\");\n if (HTML_FIELDS.has(k)) return \"html\";\n if (HEADER_FIELDS.has(k)) return \"header\";\n return inherited;\n}\n\nfunction interpolateValue(\n tmpl: string,\n variables: Record<string, unknown>,\n mode: EscapeMode,\n): string {\n return tmpl\n .replace(/\\{\\{\\{(\\w+)\\}\\}\\}/g, (_, k: string) => {\n const raw = variables[k];\n if (raw === undefined || raw === null) return \"\";\n return typeof raw === \"string\" ? raw : JSON.stringify(raw);\n })\n .replace(/\\{\\{(\\w+)\\}\\}/g, (_, k: string) => {\n const raw = variables[k];\n if (raw === undefined || raw === null) return \"\";\n const val = typeof raw === \"string\" ? raw : JSON.stringify(raw);\n if (mode === \"html\") return escapeHtml(val);\n if (mode === \"header\") return escapeHeader(val);\n return val;\n });\n}\n\nexport function renderContentNode(\n node: unknown,\n variables: Record<string, unknown>,\n mode: EscapeMode,\n): unknown {\n if (typeof node === \"string\") return interpolateValue(node, variables, mode);\n if (Array.isArray(node)) return node.map((item) => renderContentNode(item, variables, mode));\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node as Record<string, unknown>)) {\n out[key] = renderContentNode(value, variables, escapeModeFor(key, mode));\n }\n return out;\n }\n return node;\n}\n"]}
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/tools/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,OAAO;IACP,KAAK;IACL,MAAM;IACN,SAAS;IACT,QAAQ;IACR,UAAU;IACV,SAAS;IACT,UAAU;IACV,OAAO;CACC,CAAC;AACX,iEAAiE;AACjE,MAAM,CAAC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AACzC,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAU,CAAC;AAUzE,8EAA8E;AAC9E,SAAS,EAAE,CAAC,KAAc;IACxB,MAAM,IAAI,GACR,KAAK,KAAK,SAAS;QACjB,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ;YACzB,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACvC,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,E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C;YAChC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;aAAM,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9C,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;IACF,KAAK,CAAC,IAAI,CAAC,CAAC;IACZ,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AACpB,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,IAAa,EACb,SAAkC,EAClC,IAAgB;IAEhB,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IAC7E,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,iBAAiB,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAC7F,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACrC,MAAM,GAAG,GAA4B,EAAE,CAAC;QACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAA+B,CAAC,EAAE,CAAC;YAC3E,GAAG,CAAC,GAAG,CAAC,GAAG,iBAAiB,CAAC,KAAK,EAAE,SAAS,EAAE,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC;QAC3E,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { NotifkitApiError } from \"../client.js\";\n\nexport const CHANNELS = [\n \"email\",\n \"sms\",\n \"push\",\n \"webhook\",\n \"in-app\",\n \"telegram\",\n \"discord\",\n \"whatsapp\",\n \"slack\",\n] as const;\n// The server accepts contacts on every channel, in-app included.\nexport const CONTACT_CHANNELS = CHANNELS;\nexport const PRIORITIES = [\"low\", \"normal\", \"high\", \"critical\"] as const;\n\ninterface ToolResult {\n // The SDK's tool-result type carries an index signature for protocol\n // extensions; without one here an interface is not assignable to it.\n [key: string]: unknown;\n content: { type: \"text\"; text: string }[];\n isError?: boolean;\n}\n\n/** Render any handler return value as the text payload MCP clients expect. */\nfunction ok(value: unknown): ToolResult {\n const text =\n value === undefined\n ? \"Done.\"\n : typeof value === \"string\"\n ? value\n : JSON.stringify(value, null, 2);\n return { content: [{ type: \"text\", text }] };\n}\n\nfunction fail(error: unknown): ToolResult {\n const text =\n error instanceof NotifkitApiError\n ? `notifkit API error (HTTP ${error.status}): ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n/** Wrap a handler so a failed request is reported to the model instead of killing the server. */\nexport function handler<T>(fn: (args: T) => Promise<unknown>) {\n return async (args: T): Promise<ToolResult> => {\n try {\n return ok(await fn(args));\n } catch (error) {\n return fail(error);\n }\n };\n}\n\nfunction escapeHtml(unsafe: string): string {\n return String(unsafe)\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\nfunction escapeHeader(unsafe: string): string {\n return String(unsafe)\n .replace(/[\\r\\n]+/g, \" \")\n .trim();\n}\n\nexport type EscapeMode = \"html\" | \"header\" | \"text\";\nconst HTML_FIELDS = new Set([\"html\", \"htmlbody\", \"bodyhtml\", \"htmlcontent\"]);\nconst HEADER_FIELDS = new Set([\n \"subject\",\n \"title\",\n \"from\",\n \"replyto\",\n \"cc\",\n \"bcc\",\n \"preheader\",\n \"preview\",\n]);\n\nfunction escapeModeFor(key: string, inherited: EscapeMode): EscapeMode {\n const k = key.toLowerCase().replace(/[-_]/g, \"\");\n if (HTML_FIELDS.has(k)) return \"html\";\n if (HEADER_FIELDS.has(k)) return \"header\";\n return inherited;\n}\n\n// Placeholders follow the server's renderer (src/templates/render.ts) so a\n// preview shows what will be sent: `{{{path}}}` (group 1) or `{{path}}`\n// (group 2), a path being a name or a dotted path (`user.name`), with optional\n// whitespace inside the braces.\nconst PLACEHOLDER = /\\{\\{\\{\\s*(\\w+(?:\\.\\w+)*)\\s*\\}\\}\\}|\\{\\{\\s*(\\w+(?:\\.\\w+)*)\\s*\\}\\}/g;\n\n/** The value at a dotted path, reading own properties only; undefined when missing. */\nexport function valueAt(variables: Record<string, unknown>, path: string): unknown {\n let value: unknown = variables;\n for (const segment of path.split(\".\")) {\n if (value === null || typeof value !== \"object\" || !Object.hasOwn(value, segment)) {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n}\n\nfunction lookup(variables: Record<string, unknown>, path: string): string {\n const value = valueAt(variables, path);\n if (value === undefined || value === null) return \"\";\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\nfunction applyEscape(value: string, mode: EscapeMode): string {\n if (mode === \"html\") return escapeHtml(value);\n if (mode === \"header\") return escapeHeader(value);\n return value;\n}\n\n// One pass, so an inserted value is never scanned for placeholders again.\nfunction interpolateValue(\n tmpl: string,\n variables: Record<string, unknown>,\n mode: EscapeMode,\n): string {\n return tmpl.replace(\n PLACEHOLDER,\n (_, rawPath: string | undefined, escapedPath: string | undefined) =>\n rawPath !== undefined\n ? lookup(variables, rawPath)\n : applyEscape(lookup(variables, escapedPath ?? \"\"), mode),\n );\n}\n\n/** Every placeholder path used in the strings of a content tree, once each, in order. */\nexport function placeholderPaths(node: unknown): string[] {\n const paths = new Set<string>();\n const visit = (value: unknown): void => {\n if (typeof value === \"string\") {\n for (const match of value.matchAll(PLACEHOLDER)) paths.add(match[1] ?? match[2] ?? \"\");\n } else if (Array.isArray(value)) {\n value.forEach(visit);\n } else if (value && typeof value === \"object\") {\n Object.values(value).forEach(visit);\n }\n };\n visit(node);\n return [...paths];\n}\n\nexport function renderContentNode(\n node: unknown,\n variables: Record<string, unknown>,\n mode: EscapeMode,\n): unknown {\n if (typeof node === \"string\") return interpolateValue(node, variables, mode);\n if (Array.isArray(node)) return node.map((item) => renderContentNode(item, variables, mode));\n if (node && typeof node === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node as Record<string, unknown>)) {\n out[key] = renderContentNode(value, variables, escapeModeFor(key, mode));\n }\n return out;\n }\n return node;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/tools/templates.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAwMhF"}
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/tools/templates.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAoMhF"}
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { CHANNELS, handler, renderContentNode } from "./shared.js";
2
+ import { CHANNELS, handler, placeholderPaths, renderContentNode, valueAt } from "./shared.js";
3
3
  export function registerTemplatesTools(server, api) {
4
4
  server.registerTool("list_templates", {
5
5
  title: "List templates",
@@ -87,11 +87,9 @@ export function registerTemplatesTools(server, api) {
87
87
  }
88
88
  const vars = args.data ?? {};
89
89
  const rendered = renderContentNode(rawContent ?? {}, vars, "text");
90
- const jsonStr = JSON.stringify(rawContent ?? {});
91
- const placeholderMatches = Array.from(jsonStr.matchAll(/\{\{\{?(\w+)\}?\}\}/g)).map((m) => m[1]);
92
- const placeholders = Array.from(new Set(placeholderMatches));
93
- const resolvedVariables = placeholders.filter((p) => p in vars);
94
- const unresolvedVariables = placeholders.filter((p) => !(p in vars));
90
+ const placeholders = placeholderPaths(rawContent ?? {});
91
+ const resolvedVariables = placeholders.filter((p) => valueAt(vars, p) !== undefined);
92
+ const unresolvedVariables = placeholders.filter((p) => valueAt(vars, p) === undefined);
95
93
  return {
96
94
  ...(args.id ? { templateId: args.id } : {}),
97
95
  channel: templateChannel ?? "email",
@@ -1 +1 @@
1
- {"version":3,"file":"templates.js","sourceRoot":"","sources":["../../src/tools/templates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEnE,MAAM,UAAU,sBAAsB,CAAC,MAAiB,EAAE,GAAgB;IACxE,MAAM,CAAC,YAAY,CACjB,gBAAgB,EAChB;QACE,KAAK,EAAE,gBAAgB;QACvB,WAAW,EACT,2FAA2F;YAC3F,mDAAmD;QACrD,WAAW,EAAE;YACX,KAAK,EAAE,CAAC;iBACL,MAAM,EAAE;iBACR,GAAG,EAAE;iBACL,GAAG,CAAC,CAAC,CAAC;iBACN,GAAG,CAAC,GAAG,CAAC;iBACR,QAAQ,EAAE;iBACV,QAAQ,CAAC,wCAAwC,CAAC;YACrD,OAAO,EAAE,CAAC;iBACP,IAAI,CAAC,QAAQ,CAAC;iBACd,QAAQ,EAAE;iBACV,QAAQ,CAAC,mDAAmD,CAAC;YAChE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,6CAA6C,CAAC;SACrF;QACD,WAAW,EAAE,EAAE,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,IAAI,EAAE;KAC7D,EACD,OAAO,CAAC,KAAK,EAAE,IAAI,E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T,0FAA0F;YAC1F,oFAAoF;YACpF,mEAAmE;QACrE,WAAW,EAAE;YACX,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,kCAAkC,CAAC;YACtE,OAAO,EAAE,CAAC;iBACP,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;iBAC/B,QAAQ,EAAE;iBACV,QAAQ,CAAC,wCAAwC,CAAC;YACrD,IAAI,EAAE,CAAC;iBACJ,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;iBAC/B,QAAQ,EAAE;iBACV,QAAQ,CAAC,6CAA6C,CAAC;YAC1D,OAAO,EAAE,CAAC;iBACP,IAAI,CAAC,QAAQ,CAAC;iBACd,QAAQ,EAAE;iBACV,QAAQ,CAAC,+CAA+C,CAAC;SAC7D;QACD,WAAW,EAAE,EAAE,KAAK,EAAE,yBAAyB,EAAE,YAAY,EAAE,IAAI,EAAE;KACtE,EACD,OAAO,CAAC,sBAAsB,CAAC,CAChC,CAAC;AACJ,CAAC","sourcesContent":["import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { NotifkitApi } from \"../client.js\";\nimport { CHANNELS, handler, renderContentNode } from \"./shared.js\";\n\nexport function registerTemplatesTools(server: McpServer, api: NotifkitApi): void {\n server.registerTool(\n \"list_templates\",\n {\n title: \"List templates\",\n description:\n \"List registered templates with their channel and content. Supports filtering by channel, \" +\n \"topic opt-out category, or limiting result count.\",\n inputSchema: {\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Maximum number of templates to return.\"),\n channel: z\n .enum(CHANNELS)\n .optional()\n .describe(\"Only list templates that render for this channel.\"),\n topic: z.string().optional().describe(\"Only list templates tagged with this topic.\"),\n },\n annotations: { title: \"List templates\", readOnlyHint: true },\n },\n handler(async (args) => api.get(\"/v1/templates\", args)),\n );\n\n server.registerTool(\n \"get_template\",\n {\n title: \"Get a template\",\n description:\n \"Fetch one template by id, including its full per-channel content and any AI prompts.\",\n inputSchema: { id: z.string().min(1).describe(\"Template id.\") },\n annotations: { title: \"Get a template\", readOnlyHint: true },\n },\n handler(async (args) => api.get(`/v1/templates/${encodeURIComponent(args.id)}`)),\n );\n\n server.registerTool(\n \"upsert_template\",\n {\n title: \"Create or update a template\",\n description:\n \"Create a template, or overwrite an existing one with the same id. Content is a per-channel object \" +\n \"whose values may contain {{variable}} placeholders filled by send_notification's `data`; escaping \" +\n \"is decided by the destination field. Because this overwrites, call get_template first when \" +\n \"editing one that already exists.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Template id, e.g. 'order-shipped'.\"),\n channel: z.enum(CHANNELS).describe(\"Channel this template renders for.\"),\n topic: z\n .union([z.string().min(1), z.array(z.string().min(1))])\n .optional()\n .describe(\"Topic(s) this template belongs to, used for per-user topic opt-outs.\"),\n content: z\n .record(z.string(), z.unknown())\n .describe(\"Channel-specific fields, e.g. { subject, body } for email.\"),\n aiPrompts: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Optional per-field LLM prompts applied before rendering.\"),\n },\n annotations: {\n title: \"Create or update a template\",\n readOnlyHint: false,\n idempotentHint: true,\n },\n },\n handler(async (args) => api.put(\"/v1/templates\", { templates: [args] })),\n );\n\n server.registerTool(\n \"delete_template\",\n {\n title: \"Delete a template\",\n description: \"Permanently delete a registered template by its ID.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Template id to delete.\"),\n },\n annotations: {\n title: \"Delete a template\",\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n },\n handler(async (args) => {\n await api.delete(`/v1/templates/${encodeURIComponent(args.id)}`);\n return `Deleted template ${args.id}.`;\n }),\n );\n\n const previewTemplateHandler = async (args: {\n id?: string;\n content?: Record<string, unknown>;\n data?: Record<string, unknown>;\n channel?: (typeof CHANNELS)[number];\n }) => {\n if (!args.id && !args.content) {\n throw new Error(\"Provide either a template `id` or raw `content` to preview.\");\n }\n\n let rawContent = args.content;\n let templateChannel = args.channel;\n\n if (args.id) {\n const tmpl = await api.get<{\n id: string;\n channel?: (typeof CHANNELS)[number];\n content: Record<string, unknown>;\n }>(`/v1/templates/${encodeURIComponent(args.id)}`);\n if (!rawContent) {\n rawContent = tmpl.content;\n }\n if (!templateChannel && tmpl.channel) {\n templateChannel = tmpl.channel;\n }\n }\n\n const vars = args.data ?? {};\n const rendered = renderContentNode(rawContent ?? {}, vars, \"text\");\n\n const jsonStr = JSON.stringify(rawContent ?? {});\n const placeholderMatches = Array.from(jsonStr.matchAll(/\\{\\{\\{?(\\w+)\\}?\\}\\}/g)).map(\n (m) => m[1]!,\n );\n const placeholders = Array.from(new Set(placeholderMatches));\n const resolvedVariables = placeholders.filter((p) => p in vars);\n const unresolvedVariables = placeholders.filter((p) => !(p in vars));\n\n return {\n ...(args.id ? { templateId: args.id } : {}),\n channel: templateChannel ?? \"email\",\n rendered,\n resolvedVariables,\n unresolvedVariables: unresolvedVariables.length > 0 ? unresolvedVariables : undefined,\n };\n };\n\n server.registerTool(\n \"preview_template\",\n {\n title: \"Preview a template\",\n description:\n \"Dry-run render a template with sample variable data before sending. Pass an existing template \" +\n \"`id` or supply raw `content` directly. Interpolates {{variable}} placeholders and returns the \" +\n \"rendered output alongside resolved/unresolved variable names.\",\n inputSchema: {\n id: z.string().optional().describe(\"Template id to fetch and preview.\"),\n content: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Raw template content object (e.g. { subject, body }) to render without saving.\",\n ),\n data: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Sample variable data to interpolate into the template's placeholders.\"),\n channel: z\n .enum(CHANNELS)\n .optional()\n .describe(\n \"Target channel (e.g. 'email', 'sms', 'push'). Defaults to the template's channel.\",\n ),\n },\n annotations: { title: \"Preview a template\", readOnlyHint: true },\n },\n handler(previewTemplateHandler),\n );\n\n /** @deprecated Same handler as preview_template; removed at the next minor version. */\n server.registerTool(\n \"render_template\",\n {\n title: \"Render template content\",\n description:\n \"Deprecated: use preview_template, which does the same thing; this tool will be removed. \" +\n \"Render template content with variable data without dispatching any notifications. \" +\n \"Accepts either an existing template `id` or raw `content` object.\",\n inputSchema: {\n id: z.string().optional().describe(\"Template id to fetch and render.\"),\n content: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Raw template content object to render.\"),\n data: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Variables to interpolate into placeholders.\"),\n channel: z\n .enum(CHANNELS)\n .optional()\n .describe(\"Target channel. Defaults to template channel.\"),\n },\n annotations: { title: \"Render template content\", readOnlyHint: true },\n },\n handler(previewTemplateHandler),\n );\n}\n"]}
1
+ {"version":3,"file":"templates.js","sourceRoot":"","sources":["../../src/tools/templates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAE9F,MAAM,UAAU,sBAAsB,CAAC,MAAiB,EAAE,GAAgB;IACxE,MAAM,CAAC,YAAY,CACjB,gBAAgB,EAChB;QACE,KAAK,EAAE,gBAAgB;QACvB,WAAW,EACT,2FAA2F;YAC3F,mDAAmD;QACrD,WAAW,EAAE;YACX,KAAK,EAAE,CAAC;iBACL,MAAM,EAAE;iBACR,GAAG,EAAE;iBACL,GAAG,CAAC,CAAC,CAAC;iBACN,GAAG,CAAC,GAAG,CAAC;iBACR,QAAQ,EAAE;iBACV,QAAQ,CAAC,wCAAwC,CAAC;YACrD,OAAO,EAAE,CAAC;iBACP,IAAI,CAAC,QAAQ,CAAC;iBACd,QAAQ,EAAE;iBACV,QAAQ,CAAC,mDAAmD,CAAC;YAChE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,6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AC,QAAQ,EAAE,CAAC,QAAQ,CAAC,kCAAkC,CAAC;YACtE,OAAO,EAAE,CAAC;iBACP,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;iBAC/B,QAAQ,EAAE;iBACV,QAAQ,CAAC,wCAAwC,CAAC;YACrD,IAAI,EAAE,CAAC;iBACJ,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;iBAC/B,QAAQ,EAAE;iBACV,QAAQ,CAAC,6CAA6C,CAAC;YAC1D,OAAO,EAAE,CAAC;iBACP,IAAI,CAAC,QAAQ,CAAC;iBACd,QAAQ,EAAE;iBACV,QAAQ,CAAC,+CAA+C,CAAC;SAC7D;QACD,WAAW,EAAE,EAAE,KAAK,EAAE,yBAAyB,EAAE,YAAY,EAAE,IAAI,EAAE;KACtE,EACD,OAAO,CAAC,sBAAsB,CAAC,CAChC,CAAC;AACJ,CAAC","sourcesContent":["import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { NotifkitApi } from \"../client.js\";\nimport { CHANNELS, handler, placeholderPaths, renderContentNode, valueAt } from \"./shared.js\";\n\nexport function registerTemplatesTools(server: McpServer, api: NotifkitApi): void {\n server.registerTool(\n \"list_templates\",\n {\n title: \"List templates\",\n description:\n \"List registered templates with their channel and content. Supports filtering by channel, \" +\n \"topic opt-out category, or limiting result count.\",\n inputSchema: {\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Maximum number of templates to return.\"),\n channel: z\n .enum(CHANNELS)\n .optional()\n .describe(\"Only list templates that render for this channel.\"),\n topic: z.string().optional().describe(\"Only list templates tagged with this topic.\"),\n },\n annotations: { title: \"List templates\", readOnlyHint: true },\n },\n handler(async (args) => api.get(\"/v1/templates\", args)),\n );\n\n server.registerTool(\n \"get_template\",\n {\n title: \"Get a template\",\n description:\n \"Fetch one template by id, including its full per-channel content and any AI prompts.\",\n inputSchema: { id: z.string().min(1).describe(\"Template id.\") },\n annotations: { title: \"Get a template\", readOnlyHint: true },\n },\n handler(async (args) => api.get(`/v1/templates/${encodeURIComponent(args.id)}`)),\n );\n\n server.registerTool(\n \"upsert_template\",\n {\n title: \"Create or update a template\",\n description:\n \"Create a template, or overwrite an existing one with the same id. Content is a per-channel object \" +\n \"whose values may contain {{variable}} placeholders filled by send_notification's `data`; escaping \" +\n \"is decided by the destination field. Because this overwrites, call get_template first when \" +\n \"editing one that already exists.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Template id, e.g. 'order-shipped'.\"),\n channel: z.enum(CHANNELS).describe(\"Channel this template renders for.\"),\n topic: z\n .union([z.string().min(1), z.array(z.string().min(1))])\n .optional()\n .describe(\"Topic(s) this template belongs to, used for per-user topic opt-outs.\"),\n content: z\n .record(z.string(), z.unknown())\n .describe(\"Channel-specific fields, e.g. { subject, body } for email.\"),\n aiPrompts: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Optional per-field LLM prompts applied before rendering.\"),\n },\n annotations: {\n title: \"Create or update a template\",\n readOnlyHint: false,\n idempotentHint: true,\n },\n },\n handler(async (args) => api.put(\"/v1/templates\", { templates: [args] })),\n );\n\n server.registerTool(\n \"delete_template\",\n {\n title: \"Delete a template\",\n description: \"Permanently delete a registered template by its ID.\",\n inputSchema: {\n id: z.string().min(1).describe(\"Template id to delete.\"),\n },\n annotations: {\n title: \"Delete a template\",\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n },\n handler(async (args) => {\n await api.delete(`/v1/templates/${encodeURIComponent(args.id)}`);\n return `Deleted template ${args.id}.`;\n }),\n );\n\n const previewTemplateHandler = async (args: {\n id?: string;\n content?: Record<string, unknown>;\n data?: Record<string, unknown>;\n channel?: (typeof CHANNELS)[number];\n }) => {\n if (!args.id && !args.content) {\n throw new Error(\"Provide either a template `id` or raw `content` to preview.\");\n }\n\n let rawContent = args.content;\n let templateChannel = args.channel;\n\n if (args.id) {\n const tmpl = await api.get<{\n id: string;\n channel?: (typeof CHANNELS)[number];\n content: Record<string, unknown>;\n }>(`/v1/templates/${encodeURIComponent(args.id)}`);\n if (!rawContent) {\n rawContent = tmpl.content;\n }\n if (!templateChannel && tmpl.channel) {\n templateChannel = tmpl.channel;\n }\n }\n\n const vars = args.data ?? {};\n const rendered = renderContentNode(rawContent ?? {}, vars, \"text\");\n\n const placeholders = placeholderPaths(rawContent ?? {});\n const resolvedVariables = placeholders.filter((p) => valueAt(vars, p) !== undefined);\n const unresolvedVariables = placeholders.filter((p) => valueAt(vars, p) === undefined);\n\n return {\n ...(args.id ? { templateId: args.id } : {}),\n channel: templateChannel ?? \"email\",\n rendered,\n resolvedVariables,\n unresolvedVariables: unresolvedVariables.length > 0 ? unresolvedVariables : undefined,\n };\n };\n\n server.registerTool(\n \"preview_template\",\n {\n title: \"Preview a template\",\n description:\n \"Dry-run render a template with sample variable data before sending. Pass an existing template \" +\n \"`id` or supply raw `content` directly. Interpolates {{variable}} placeholders and returns the \" +\n \"rendered output alongside resolved/unresolved variable names.\",\n inputSchema: {\n id: z.string().optional().describe(\"Template id to fetch and preview.\"),\n content: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Raw template content object (e.g. { subject, body }) to render without saving.\",\n ),\n data: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Sample variable data to interpolate into the template's placeholders.\"),\n channel: z\n .enum(CHANNELS)\n .optional()\n .describe(\n \"Target channel (e.g. 'email', 'sms', 'push'). Defaults to the template's channel.\",\n ),\n },\n annotations: { title: \"Preview a template\", readOnlyHint: true },\n },\n handler(previewTemplateHandler),\n );\n\n /** @deprecated Same handler as preview_template; removed at the next minor version. */\n server.registerTool(\n \"render_template\",\n {\n title: \"Render template content\",\n description:\n \"Deprecated: use preview_template, which does the same thing; this tool will be removed. \" +\n \"Render template content with variable data without dispatching any notifications. \" +\n \"Accepts either an existing template `id` or raw `content` object.\",\n inputSchema: {\n id: z.string().optional().describe(\"Template id to fetch and render.\"),\n content: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Raw template content object to render.\"),\n data: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Variables to interpolate into placeholders.\"),\n channel: z\n .enum(CHANNELS)\n .optional()\n .describe(\"Target channel. Defaults to template channel.\"),\n },\n annotations: { title: \"Render template content\", readOnlyHint: true },\n },\n handler(previewTemplateHandler),\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"workflows.d.ts","sourceRoot":"","sources":["../../src/tools/workflows.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAwJhF"}
1
+ {"version":3,"file":"workflows.d.ts","sourceRoot":"","sources":["../../src/tools/workflows.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI,CAiKhF"}
@@ -27,7 +27,14 @@ export function registerWorkflowsTools(server, api) {
27
27
  action: z.literal("waitForEvent"),
28
28
  event: z.string().describe("Event name to wait for, as passed to ingest_event."),
29
29
  options: z
30
- .object({ timeout: z.string().optional().describe("e.g. '24h'.") })
30
+ .object({
31
+ timeout: z.string().optional().describe("e.g. '24h'."),
32
+ match: z
33
+ .record(z.string(), z.unknown())
34
+ .optional()
35
+ .describe("Fields the event must carry to wake this instance, e.g. { userId: 'u1' }. " +
36
+ "Without it any event of that name wakes every waiting instance."),
37
+ })
31
38
  .optional()
32
39
  .describe("Give a timeout so the instance cannot wait forever."),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,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,iCAAiC,CAAC,EAAE;QAC1F,WAAW,EAAE;YACX,KAAK,EAAE,uBAAuB;YAC9B,YAAY,EAAE,KAAK;YACnB,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE,IAAI;SACrB;KACF,EACD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;QACrB,MAAM,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,2BAA2B,kBAAkB,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;QAC9F,OAAO,+BAA+B,IAAI,CAAC,UAAU,GAAG,CAAC;IAC3D,CAAC,CAAC,CACH,CAAC;IAEF,MAAM,CAAC,YAAY,CACjB,cAAc,EACd;QACE,KAAK,EAAE,iBAAiB;QACxB,WAAW,EACT,0FAA0F;YAC1F,kGAAkG;YAClG,gEAAgE;QAClE,WAAW,EAAE;YACX,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,sDAAsD,CAAC;YACxF,UAAU,EAAE,CAAC;iBACV,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;iBAC/B,QAAQ,CAAC,wDAAwD,CAAC;SACtE;QACD,WAAW,EAAE,EAAE,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE;KACtF,EACD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC,CACtD,CAAC;AACJ,CAAC","sourcesContent":["import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { NotifkitApi } from \"../client.js\";\nimport { handler } from \"./shared.js\";\n\nexport function registerWorkflowsTools(server: McpServer, api: NotifkitApi): void {\n server.registerTool(\n \"create_workflow\",\n {\n title: \"Create a workflow\",\n description:\n \"Define a named multi-step sequence — the way to build a drip, an onboarding series, or a reminder \" +\n \"chain rather than a single send. Steps run in order and are one of: `notify` (send, using the \" +\n \"same fields as send_notification), `wait` (pause for a duration like '1h' or '3d'), or \" +\n \"`waitForEvent` (block until ingest_event reports a named event, with an optional timeout). A \" +\n \"notify step with no target inherits the user the instance was triggered for. Creating a workflow \" +\n \"does not run it — call trigger_workflow per user.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Workflow name, used later by trigger_workflow.\"),\n steps: z\n .array(\n z.union([\n z.object({\n action: z.literal(\"notify\"),\n payload: z\n .record(z.string(), z.unknown())\n .describe(\n \"Same shape as send_notification's arguments. Omit the target to use the instance's own user.\",\n ),\n }),\n z.object({\n action: z.literal(\"wait\"),\n duration: z.string().describe(\"Duration string, e.g. '5m', '1h', '3d'.\"),\n }),\n z.object({\n action: z.literal(\"waitForEvent\"),\n event: z.string().describe(\"Event name to wait for, as passed to ingest_event.\"),\n options: z\n .object({ timeout: z.string().optional().describe(\"e.g. '24h'.\") })\n .optional()\n .describe(\"Give a timeout so the instance cannot wait forever.\"),\n }),\n ]),\n )\n .min(1)\n .describe(\"Ordered steps.\"),\n },\n annotations: { title: \"Create a workflow\", readOnlyHint: false, idempotentHint: true },\n },\n handler(async (args) => api.post(\"/v1/workflows\", args)),\n );\n\n server.registerTool(\n \"list_workflows\",\n {\n title: \"List workflows\",\n description:\n \"List registered workflow definitions and their steps. Call this to find the name to pass to \" +\n \"trigger_workflow, or to check a sequence before triggering it. Supports filtering by search keyword.\",\n inputSchema: {\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Maximum number of workflow definitions to return.\"),\n search: z\n .string()\n .optional()\n .describe(\"Filter workflow definitions whose name contains this search keyword.\"),\n },\n annotations: { title: \"List workflows\", readOnlyHint: true },\n },\n handler(async (args) => api.get(\"/v1/workflows\", args)),\n );\n\n server.registerTool(\n \"trigger_workflow\",\n {\n title: \"Trigger a workflow\",\n description:\n \"Start one run of a registered workflow, optionally for a specific user, and return the instance \" +\n \"id. Each call starts an independent instance, so triggering the same workflow twice for one user \" +\n \"enrols them twice. Track the returned instance with get_workflow_run.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Name of the workflow to run.\"),\n user: z\n .string()\n .min(1)\n .optional()\n .describe(\"User id this run is for. Notify steps default to them.\"),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Data made available to the run's steps.\"),\n },\n annotations: { title: \"Trigger a workflow\", readOnlyHint: false, idempotentHint: false },\n },\n handler(async (args) => api.post(\"/v1/workflows/trigger\", args)),\n );\n\n server.registerTool(\n \"get_workflow_run\",\n {\n title: \"Get a workflow run\",\n description:\n \"Fetch one workflow instance by id: which step it is on, its status, and what it is waiting for. \" +\n \"Use this to check on a run started by trigger_workflow.\",\n inputSchema: { instanceId: z.string().min(1).describe(\"Workflow instance id.\") },\n annotations: { title: \"Get a workflow run\", readOnlyHint: true },\n },\n handler(async (args) =>\n api.get(`/v1/workflows/instances/${encodeURIComponent(args.instanceId)}`),\n ),\n );\n\n server.registerTool(\n \"cancel_workflow_run\",\n {\n title: \"Cancel a workflow run\",\n description:\n \"Stop a running or suspended workflow instance so its remaining steps never fire. This does not \" +\n \"recall notifications already sent, and it cannot be undone — confirm with the user before \" +\n \"cancelling a run you did not start in this session.\",\n inputSchema: { instanceId: z.string().min(1).describe(\"Workflow instance id to cancel.\") },\n annotations: {\n title: \"Cancel a workflow run\",\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n },\n handler(async (args) => {\n await api.request(\"DELETE\", `/v1/workflows/instances/${encodeURIComponent(args.instanceId)}`);\n return `Cancelled workflow instance ${args.instanceId}.`;\n }),\n );\n\n server.registerTool(\n \"ingest_event\",\n {\n title: \"Ingest an event\",\n description:\n \"Report that something happened in your product. Workflow instances parked on a matching \" +\n \"`waitForEvent` step resume. Call this to unblock a waiting sequence, e.g. emitting 'order.paid' \" +\n \"so an abandoned-cart workflow stops before its reminder fires.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Event name, matching a workflow's waitForEvent step.\"),\n properties: z\n .record(z.string(), z.unknown())\n .describe(\"Event payload. Include the user id the event is about.\"),\n },\n annotations: { title: \"Ingest an event\", readOnlyHint: false, idempotentHint: false },\n },\n handler(async (args) => api.post(\"/v1/events\", args)),\n );\n}\n"]}
1
+ {"version":3,"file":"workflows.js","sourceRoot":"","sources":["../../src/tools/workflows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,MAAM,UAAU,sBAAsB,CAAC,MAAiB,EAAE,GAAgB;IACxE,MAAM,CAAC,YAAY,CACjB,iBAAiB,EACjB;QACE,KAAK,EAAE,mBAAmB;QAC1B,WAAW,EACT,oGAAoG;YACpG,gGAAgG;YAChG,yFAAyF;YACzF,+FAA+F;YAC/F,mGAAmG;YACnG,mDAAmD;QACrD,WAAW,EAAE;YACX,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,gDAAgD,CAAC;YAClF,KAAK,EAAE,CAAC;iBACL,KAAK,CACJ,CAAC,CAAC,KAAK,CAAC;gBACN,CAAC,CAAC,MAAM,CAAC;oBACP,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC;oBAC3B,OAAO,EAAE,CAAC;yBACP,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;yBAC/B,QAAQ,CACP,8FAA8F,CAC/F;iBACJ,CAAC;gBACF,CAAC,CAAC,MAAM,CAAC;oBACP,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;oBACzB,QAAQ,EAAE,CAAC,CAAC,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E,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;iBAC/B,QAAQ,CAAC,wDAAwD,CAAC;SACtE;QACD,WAAW,EAAE,EAAE,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE;KACtF,EACD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC,CACtD,CAAC;AACJ,CAAC","sourcesContent":["import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { NotifkitApi } from \"../client.js\";\nimport { handler } from \"./shared.js\";\n\nexport function registerWorkflowsTools(server: McpServer, api: NotifkitApi): void {\n server.registerTool(\n \"create_workflow\",\n {\n title: \"Create a workflow\",\n description:\n \"Define a named multi-step sequence — the way to build a drip, an onboarding series, or a reminder \" +\n \"chain rather than a single send. Steps run in order and are one of: `notify` (send, using the \" +\n \"same fields as send_notification), `wait` (pause for a duration like '1h' or '3d'), or \" +\n \"`waitForEvent` (block until ingest_event reports a named event, with an optional timeout). A \" +\n \"notify step with no target inherits the user the instance was triggered for. Creating a workflow \" +\n \"does not run it — call trigger_workflow per user.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Workflow name, used later by trigger_workflow.\"),\n steps: z\n .array(\n z.union([\n z.object({\n action: z.literal(\"notify\"),\n payload: z\n .record(z.string(), z.unknown())\n .describe(\n \"Same shape as send_notification's arguments. Omit the target to use the instance's own user.\",\n ),\n }),\n z.object({\n action: z.literal(\"wait\"),\n duration: z.string().describe(\"Duration string, e.g. '5m', '1h', '3d'.\"),\n }),\n z.object({\n action: z.literal(\"waitForEvent\"),\n event: z.string().describe(\"Event name to wait for, as passed to ingest_event.\"),\n options: z\n .object({\n timeout: z.string().optional().describe(\"e.g. '24h'.\"),\n match: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Fields the event must carry to wake this instance, e.g. { userId: 'u1' }. \" +\n \"Without it any event of that name wakes every waiting instance.\",\n ),\n })\n .optional()\n .describe(\"Give a timeout so the instance cannot wait forever.\"),\n }),\n ]),\n )\n .min(1)\n .describe(\"Ordered steps.\"),\n },\n annotations: { title: \"Create a workflow\", readOnlyHint: false, idempotentHint: true },\n },\n handler(async (args) => api.post(\"/v1/workflows\", args)),\n );\n\n server.registerTool(\n \"list_workflows\",\n {\n title: \"List workflows\",\n description:\n \"List registered workflow definitions and their steps. Call this to find the name to pass to \" +\n \"trigger_workflow, or to check a sequence before triggering it. Supports filtering by search keyword.\",\n inputSchema: {\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .describe(\"Maximum number of workflow definitions to return.\"),\n search: z\n .string()\n .optional()\n .describe(\"Filter workflow definitions whose name contains this search keyword.\"),\n },\n annotations: { title: \"List workflows\", readOnlyHint: true },\n },\n handler(async (args) => api.get(\"/v1/workflows\", args)),\n );\n\n server.registerTool(\n \"trigger_workflow\",\n {\n title: \"Trigger a workflow\",\n description:\n \"Start one run of a registered workflow, optionally for a specific user, and return the instance \" +\n \"id. Each call starts an independent instance, so triggering the same workflow twice for one user \" +\n \"enrols them twice. Track the returned instance with get_workflow_run.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Name of the workflow to run.\"),\n user: z\n .string()\n .min(1)\n .optional()\n .describe(\"User id this run is for. Notify steps default to them.\"),\n input: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Data made available to the run's steps.\"),\n },\n annotations: { title: \"Trigger a workflow\", readOnlyHint: false, idempotentHint: false },\n },\n handler(async (args) => api.post(\"/v1/workflows/trigger\", args)),\n );\n\n server.registerTool(\n \"get_workflow_run\",\n {\n title: \"Get a workflow run\",\n description:\n \"Fetch one workflow instance by id: which step it is on, its status, and what it is waiting for. \" +\n \"Use this to check on a run started by trigger_workflow.\",\n inputSchema: { instanceId: z.string().min(1).describe(\"Workflow instance id.\") },\n annotations: { title: \"Get a workflow run\", readOnlyHint: true },\n },\n handler(async (args) =>\n api.get(`/v1/workflows/instances/${encodeURIComponent(args.instanceId)}`),\n ),\n );\n\n server.registerTool(\n \"cancel_workflow_run\",\n {\n title: \"Cancel a workflow run\",\n description:\n \"Stop a running or suspended workflow instance so its remaining steps never fire. This does not \" +\n \"recall notifications already sent, and it cannot be undone — confirm with the user before \" +\n \"cancelling a run you did not start in this session.\",\n inputSchema: { instanceId: z.string().min(1).describe(\"Workflow instance id to cancel.\") },\n annotations: {\n title: \"Cancel a workflow run\",\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n },\n handler(async (args) => {\n await api.request(\"DELETE\", `/v1/workflows/instances/${encodeURIComponent(args.instanceId)}`);\n return `Cancelled workflow instance ${args.instanceId}.`;\n }),\n );\n\n server.registerTool(\n \"ingest_event\",\n {\n title: \"Ingest an event\",\n description:\n \"Report that something happened in your product. Workflow instances parked on a matching \" +\n \"`waitForEvent` step resume. Call this to unblock a waiting sequence, e.g. emitting 'order.paid' \" +\n \"so an abandoned-cart workflow stops before its reminder fires.\",\n inputSchema: {\n name: z.string().min(1).describe(\"Event name, matching a workflow's waitForEvent step.\"),\n properties: z\n .record(z.string(), z.unknown())\n .describe(\"Event payload. Include the user id the event is about.\"),\n },\n annotations: { title: \"Ingest an event\", readOnlyHint: false, idempotentHint: false },\n },\n handler(async (args) => api.post(\"/v1/events\", args)),\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notifkit/mcp",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Model Context Protocol server for notifkit — drive sends, templates, users, and workflows from a terminal agent.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -90,25 +90,65 @@ function escapeModeFor(key: string, inherited: EscapeMode): EscapeMode {
90
90
  return inherited;
91
91
  }
92
92
 
93
+ // Placeholders follow the server's renderer (src/templates/render.ts) so a
94
+ // preview shows what will be sent: `{{{path}}}` (group 1) or `{{path}}`
95
+ // (group 2), a path being a name or a dotted path (`user.name`), with optional
96
+ // whitespace inside the braces.
97
+ const PLACEHOLDER = /\{\{\{\s*(\w+(?:\.\w+)*)\s*\}\}\}|\{\{\s*(\w+(?:\.\w+)*)\s*\}\}/g;
98
+
99
+ /** The value at a dotted path, reading own properties only; undefined when missing. */
100
+ export function valueAt(variables: Record<string, unknown>, path: string): unknown {
101
+ let value: unknown = variables;
102
+ for (const segment of path.split(".")) {
103
+ if (value === null || typeof value !== "object" || !Object.hasOwn(value, segment)) {
104
+ return undefined;
105
+ }
106
+ value = (value as Record<string, unknown>)[segment];
107
+ }
108
+ return value;
109
+ }
110
+
111
+ function lookup(variables: Record<string, unknown>, path: string): string {
112
+ const value = valueAt(variables, path);
113
+ if (value === undefined || value === null) return "";
114
+ return typeof value === "string" ? value : JSON.stringify(value);
115
+ }
116
+
117
+ function applyEscape(value: string, mode: EscapeMode): string {
118
+ if (mode === "html") return escapeHtml(value);
119
+ if (mode === "header") return escapeHeader(value);
120
+ return value;
121
+ }
122
+
123
+ // One pass, so an inserted value is never scanned for placeholders again.
93
124
  function interpolateValue(
94
125
  tmpl: string,
95
126
  variables: Record<string, unknown>,
96
127
  mode: EscapeMode,
97
128
  ): string {
98
- return tmpl
99
- .replace(/\{\{\{(\w+)\}\}\}/g, (_, k: string) => {
100
- const raw = variables[k];
101
- if (raw === undefined || raw === null) return "";
102
- return typeof raw === "string" ? raw : JSON.stringify(raw);
103
- })
104
- .replace(/\{\{(\w+)\}\}/g, (_, k: string) => {
105
- const raw = variables[k];
106
- if (raw === undefined || raw === null) return "";
107
- const val = typeof raw === "string" ? raw : JSON.stringify(raw);
108
- if (mode === "html") return escapeHtml(val);
109
- if (mode === "header") return escapeHeader(val);
110
- return val;
111
- });
129
+ return tmpl.replace(
130
+ PLACEHOLDER,
131
+ (_, rawPath: string | undefined, escapedPath: string | undefined) =>
132
+ rawPath !== undefined
133
+ ? lookup(variables, rawPath)
134
+ : applyEscape(lookup(variables, escapedPath ?? ""), mode),
135
+ );
136
+ }
137
+
138
+ /** Every placeholder path used in the strings of a content tree, once each, in order. */
139
+ export function placeholderPaths(node: unknown): string[] {
140
+ const paths = new Set<string>();
141
+ const visit = (value: unknown): void => {
142
+ if (typeof value === "string") {
143
+ for (const match of value.matchAll(PLACEHOLDER)) paths.add(match[1] ?? match[2] ?? "");
144
+ } else if (Array.isArray(value)) {
145
+ value.forEach(visit);
146
+ } else if (value && typeof value === "object") {
147
+ Object.values(value).forEach(visit);
148
+ }
149
+ };
150
+ visit(node);
151
+ return [...paths];
112
152
  }
113
153
 
114
154
  export function renderContentNode(
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import type { NotifkitApi } from "../client.js";
4
- import { CHANNELS, handler, renderContentNode } from "./shared.js";
4
+ import { CHANNELS, handler, placeholderPaths, renderContentNode, valueAt } from "./shared.js";
5
5
 
6
6
  export function registerTemplatesTools(server: McpServer, api: NotifkitApi): void {
7
7
  server.registerTool(
@@ -126,13 +126,9 @@ export function registerTemplatesTools(server: McpServer, api: NotifkitApi): voi
126
126
  const vars = args.data ?? {};
127
127
  const rendered = renderContentNode(rawContent ?? {}, vars, "text");
128
128
 
129
- const jsonStr = JSON.stringify(rawContent ?? {});
130
- const placeholderMatches = Array.from(jsonStr.matchAll(/\{\{\{?(\w+)\}?\}\}/g)).map(
131
- (m) => m[1]!,
132
- );
133
- const placeholders = Array.from(new Set(placeholderMatches));
134
- const resolvedVariables = placeholders.filter((p) => p in vars);
135
- const unresolvedVariables = placeholders.filter((p) => !(p in vars));
129
+ const placeholders = placeholderPaths(rawContent ?? {});
130
+ const resolvedVariables = placeholders.filter((p) => valueAt(vars, p) !== undefined);
131
+ const unresolvedVariables = placeholders.filter((p) => valueAt(vars, p) === undefined);
136
132
 
137
133
  return {
138
134
  ...(args.id ? { templateId: args.id } : {}),
@@ -36,7 +36,16 @@ export function registerWorkflowsTools(server: McpServer, api: NotifkitApi): voi
36
36
  action: z.literal("waitForEvent"),
37
37
  event: z.string().describe("Event name to wait for, as passed to ingest_event."),
38
38
  options: z
39
- .object({ timeout: z.string().optional().describe("e.g. '24h'.") })
39
+ .object({
40
+ timeout: z.string().optional().describe("e.g. '24h'."),
41
+ match: z
42
+ .record(z.string(), z.unknown())
43
+ .optional()
44
+ .describe(
45
+ "Fields the event must carry to wake this instance, e.g. { userId: 'u1' }. " +
46
+ "Without it any event of that name wakes every waiting instance.",
47
+ ),
48
+ })
40
49
  .optional()
41
50
  .describe("Give a timeout so the instance cannot wait forever."),
42
51
  }),