posterly-mcp-server 0.44.0 → 0.45.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.
Files changed (155) hide show
  1. package/README.md +310 -111
  2. package/dist/index.js +190 -894
  3. package/dist/lib/alias-transport.d.ts +84 -0
  4. package/dist/lib/alias-transport.js +193 -0
  5. package/dist/lib/api-client.d.ts +18 -0
  6. package/dist/lib/api-client.js +55 -0
  7. package/dist/lib/preview-token-core.d.ts +62 -0
  8. package/dist/lib/preview-token-core.js +131 -0
  9. package/dist/lib/preview-token.d.ts +23 -0
  10. package/dist/lib/preview-token.js +44 -0
  11. package/dist/lib/tool-registry.d.ts +246 -0
  12. package/dist/lib/tool-registry.js +394 -0
  13. package/dist/lib/tool-runtime.d.ts +68 -0
  14. package/dist/lib/tool-runtime.js +85 -0
  15. package/dist/lib/version.d.ts +1 -1
  16. package/dist/lib/version.js +1 -1
  17. package/dist/tools/audit-google-business-profile.js +1 -1
  18. package/dist/tools/connect-account.d.ts +4 -4
  19. package/dist/tools/connect-account.js +2 -2
  20. package/dist/tools/create-connect-session.d.ts +2 -2
  21. package/dist/tools/create-connect-session.js +2 -2
  22. package/dist/tools/create-post.d.ts +6 -6
  23. package/dist/tools/create-post.js +3 -3
  24. package/dist/tools/create-posts-batch.d.ts +4 -4
  25. package/dist/tools/create-webhook.d.ts +2 -2
  26. package/dist/tools/delete-post.d.ts +34 -10
  27. package/dist/tools/delete-post.js +52 -16
  28. package/dist/tools/generate-captions.d.ts +2 -2
  29. package/dist/tools/generate-image.d.ts +4 -4
  30. package/dist/tools/generate-image.js +2 -2
  31. package/dist/tools/generate-video.d.ts +6 -6
  32. package/dist/tools/generate-video.js +1 -1
  33. package/dist/tools/get-agent-signup-info.js +2 -2
  34. package/dist/tools/get-post.d.ts +16 -1
  35. package/dist/tools/get-post.js +35 -19
  36. package/dist/tools/list-accounts.d.ts +49 -3
  37. package/dist/tools/list-accounts.js +148 -33
  38. package/dist/tools/list-analytics.d.ts +111 -0
  39. package/dist/tools/list-analytics.js +393 -0
  40. package/dist/tools/list-brands.d.ts +38 -3
  41. package/dist/tools/list-brands.js +138 -20
  42. package/dist/tools/list-comments.d.ts +29 -9
  43. package/dist/tools/list-comments.js +75 -34
  44. package/dist/tools/list-conversations.d.ts +32 -9
  45. package/dist/tools/list-conversations.js +63 -27
  46. package/dist/tools/list-google-business-media.js +1 -1
  47. package/dist/tools/list-google-business-reviews.d.ts +32 -9
  48. package/dist/tools/list-google-business-reviews.js +77 -52
  49. package/dist/tools/list-jobs.d.ts +60 -0
  50. package/dist/tools/list-jobs.js +81 -0
  51. package/dist/tools/list-platforms.d.ts +62 -3
  52. package/dist/tools/list-platforms.js +118 -9
  53. package/dist/tools/list-posts.d.ts +2 -2
  54. package/dist/tools/manage-comment.d.ts +102 -0
  55. package/dist/tools/manage-comment.js +125 -0
  56. package/dist/tools/manage-conversation.d.ts +79 -0
  57. package/dist/tools/manage-conversation.js +75 -0
  58. package/dist/tools/manage-google-business-media.d.ts +103 -0
  59. package/dist/tools/manage-google-business-media.js +126 -0
  60. package/dist/tools/manage-google-business-review.d.ts +146 -0
  61. package/dist/tools/manage-google-business-review.js +115 -0
  62. package/dist/tools/manage-oauth-client.d.ts +121 -0
  63. package/dist/tools/manage-oauth-client.js +94 -0
  64. package/dist/tools/manage-webhook.d.ts +99 -0
  65. package/dist/tools/manage-webhook.js +87 -0
  66. package/dist/tools/start-signup.d.ts +2 -2
  67. package/dist/tools/submit-agent-feedback.d.ts +4 -4
  68. package/dist/tools/trigger-platform-helper.d.ts +2 -2
  69. package/dist/tools/update-post.d.ts +62 -11
  70. package/dist/tools/update-post.js +79 -26
  71. package/dist/tools/upload-media.d.ts +32 -9
  72. package/dist/tools/upload-media.js +54 -18
  73. package/dist/tools/validate-post.d.ts +4 -4
  74. package/dist/tools/whoami.d.ts +15 -2
  75. package/dist/tools/whoami.js +221 -25
  76. package/package.json +5 -3
  77. package/scripts/test-alias-transport.mjs +368 -0
  78. package/scripts/test-client-header-sanitization.mjs +78 -0
  79. package/scripts/test-tool-annotations.mjs +38 -17
  80. package/server.json +9 -2
  81. package/src/index.ts +227 -1443
  82. package/src/lib/alias-transport.ts +233 -0
  83. package/src/lib/api-client.ts +65 -0
  84. package/src/lib/preview-token-core.ts +157 -0
  85. package/src/lib/preview-token.ts +54 -0
  86. package/src/lib/tool-registry.ts +538 -0
  87. package/src/lib/tool-runtime.ts +117 -0
  88. package/src/lib/version.ts +1 -1
  89. package/src/tools/audit-google-business-profile.ts +1 -1
  90. package/src/tools/connect-account.ts +2 -2
  91. package/src/tools/create-connect-session.ts +2 -2
  92. package/src/tools/create-post.ts +3 -3
  93. package/src/tools/delete-post.ts +60 -19
  94. package/src/tools/generate-image.ts +2 -2
  95. package/src/tools/generate-video.ts +1 -1
  96. package/src/tools/get-agent-signup-info.ts +2 -2
  97. package/src/tools/get-post.ts +35 -21
  98. package/src/tools/list-accounts.ts +187 -39
  99. package/src/tools/list-analytics.ts +444 -0
  100. package/src/tools/list-brands.ts +162 -26
  101. package/src/tools/list-comments.ts +86 -43
  102. package/src/tools/list-conversations.ts +81 -39
  103. package/src/tools/list-google-business-media.ts +1 -1
  104. package/src/tools/list-google-business-reviews.ts +93 -64
  105. package/src/tools/list-jobs.ts +91 -0
  106. package/src/tools/list-platforms.ts +135 -11
  107. package/src/tools/manage-comment.ts +142 -0
  108. package/src/tools/manage-conversation.ts +89 -0
  109. package/src/tools/manage-google-business-media.ts +147 -0
  110. package/src/tools/manage-google-business-review.ts +139 -0
  111. package/src/tools/manage-oauth-client.ts +116 -0
  112. package/src/tools/manage-webhook.ts +103 -0
  113. package/src/tools/update-post.ts +106 -39
  114. package/src/tools/upload-media.ts +76 -28
  115. package/src/tools/whoami.ts +253 -30
  116. package/tool-annotations.json +76 -149
  117. package/tool-registry.json +2085 -0
  118. package/src/tools/add-google-business-media.ts +0 -50
  119. package/src/tools/create-oauth-client.ts +0 -36
  120. package/src/tools/delete-comment.ts +0 -29
  121. package/src/tools/delete-google-business-media.ts +0 -30
  122. package/src/tools/delete-google-business-review-reply.ts +0 -30
  123. package/src/tools/delete-oauth-client.ts +0 -23
  124. package/src/tools/delete-post-group.ts +0 -17
  125. package/src/tools/delete-webhook.ts +0 -17
  126. package/src/tools/get-account-analytics.ts +0 -171
  127. package/src/tools/get-brand-profile.ts +0 -86
  128. package/src/tools/get-brand.ts +0 -34
  129. package/src/tools/get-comment.ts +0 -47
  130. package/src/tools/get-connect-link.ts +0 -61
  131. package/src/tools/get-connect-session.ts +0 -63
  132. package/src/tools/get-conversation.ts +0 -44
  133. package/src/tools/get-google-business-review-link.ts +0 -30
  134. package/src/tools/get-image-job.ts +0 -36
  135. package/src/tools/get-learned-voice.ts +0 -31
  136. package/src/tools/get-mcp-status.ts +0 -212
  137. package/src/tools/get-performance-profile.ts +0 -47
  138. package/src/tools/get-platform-schema.ts +0 -56
  139. package/src/tools/get-post-analytics.ts +0 -243
  140. package/src/tools/get-post-insights.ts +0 -60
  141. package/src/tools/get-post-missing.ts +0 -16
  142. package/src/tools/get-video-job.ts +0 -36
  143. package/src/tools/list-brand-accounts.ts +0 -36
  144. package/src/tools/reply-google-business-review.ts +0 -32
  145. package/src/tools/reply-to-comment.ts +0 -30
  146. package/src/tools/send-message.ts +0 -28
  147. package/src/tools/suggest-google-business-review-reply.ts +0 -44
  148. package/src/tools/sync-inbox.ts +0 -28
  149. package/src/tools/test-webhook.ts +0 -18
  150. package/src/tools/update-comment.ts +0 -31
  151. package/src/tools/update-oauth-client.ts +0 -38
  152. package/src/tools/update-post-release-id.ts +0 -25
  153. package/src/tools/update-post-status.ts +0 -31
  154. package/src/tools/update-webhook.ts +0 -36
  155. package/src/tools/upload-media-from-url.ts +0 -33
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Pure, dependency-free helpers over the MCP tool registry
3
+ * (mcp-server/tool-registry.json). Shared by BOTH surfaces:
4
+ * - the npm stdio package (mcp-server/src/index.ts, alias-transport.ts)
5
+ * - the hosted endpoint (lib/mcp/tool-registry.ts re-exports these with the
6
+ * registry bound)
7
+ *
8
+ * This module never imports the JSON itself: each surface loads the registry
9
+ * its own way (createRequire on stdio, a static JSON import on hosted) and
10
+ * passes it in. Keep it free of Node, Next, and zod imports so it compiles
11
+ * unchanged under both the package tsconfig and the app tsconfig.
12
+ */
13
+ export type ToolsetName = string;
14
+ export type ConfirmLevel = 'none' | 'confirm' | 'preview';
15
+ export type ToolSurface = 'hosted' | 'stdio';
16
+ export type ModeSelector = 'view' | 'action' | 'type' | 'params';
17
+ export type ExceptionCategory = 'money' | 'secret' | 'signup' | 'publishing' | 'ai_generation' | 'feedback' | 'connect' | 'single_action' | 'session' | 'dispatcher' | 'report';
18
+ export interface ModeParamSpec {
19
+ type?: 'string' | 'integer' | 'number' | 'boolean' | 'array' | 'object';
20
+ required?: boolean;
21
+ default?: unknown;
22
+ min?: number;
23
+ max?: number;
24
+ enum?: Array<string | number>;
25
+ /** Keep an explicit null (for example workspace_id: null clears a webhook's workspace). */
26
+ nullable?: boolean;
27
+ }
28
+ /** One view (read) or action (write) inside a multi-mode tool. */
29
+ export interface ToolModeEntry {
30
+ label: string;
31
+ destructive?: boolean;
32
+ idempotent?: boolean;
33
+ openWorld?: boolean;
34
+ confirm?: ConfirmLevel;
35
+ /** Preview actions whose confirm may be used once only (public writes). */
36
+ nonce?: boolean;
37
+ /** When present, the only params this mode accepts (besides the selector, confirm, preview_id). */
38
+ params?: Record<string, ModeParamSpec>;
39
+ /**
40
+ * Param-driven tools (selector "params") only: this mode is chosen when any
41
+ * of these params is present. The one mode without `when` is the default.
42
+ */
43
+ when?: string[];
44
+ }
45
+ export interface ToolRegistryTool {
46
+ set: ToolsetName;
47
+ label: string;
48
+ /** Surfaces that register this tool. Defaults to both. */
49
+ surfaces?: ToolSurface[];
50
+ exception?: {
51
+ category: ExceptionCategory;
52
+ reason: string;
53
+ };
54
+ /** Single-mode tools carry their hints here; multi-mode tools derive them from views/actions. */
55
+ readOnly?: boolean;
56
+ destructive?: boolean;
57
+ idempotent?: boolean;
58
+ openWorld?: boolean;
59
+ confirm?: ConfirmLevel;
60
+ /**
61
+ * How a multi-mode tool picks its mode: an enum param (view/action/type), or
62
+ * "params" when the mode follows from which params are present (for example
63
+ * update_post with status vs content fields). Param-driven modes are still
64
+ * recorded as views/actions so the action count is derived from the registry.
65
+ */
66
+ selector?: ModeSelector;
67
+ /** Default view/action when the selector param is omitted. */
68
+ defaultMode?: string;
69
+ views?: Record<string, ToolModeEntry>;
70
+ actions?: Record<string, ToolModeEntry>;
71
+ }
72
+ export interface ToolRegistryAlias {
73
+ target: string;
74
+ /** Params forced onto the translated call (inject wins over caller args). */
75
+ inject?: Record<string, unknown>;
76
+ /** Old param name -> new param name. */
77
+ rename?: Record<string, string>;
78
+ /** Accept confirm:true without preview_id until sunset (per call, never stored on shared context). */
79
+ legacyConfirm?: boolean;
80
+ /**
81
+ * Param-driven targets (selector "params") only: the mode the old tool
82
+ * always ran in, so for example get_comment without comment_id is still
83
+ * rejected instead of silently listing every comment.
84
+ */
85
+ mode?: string;
86
+ added: string;
87
+ sunset: string;
88
+ }
89
+ export interface ToolRegistry {
90
+ $comment?: string;
91
+ version: number;
92
+ designRules: 'off' | 'on';
93
+ budgets: {
94
+ maxTotal: number;
95
+ maxCore: number;
96
+ };
97
+ sunset: string | null;
98
+ toolsets: Record<ToolsetName, {
99
+ label: string;
100
+ description: string;
101
+ alwaysOn?: boolean;
102
+ surfaces?: ToolSurface[];
103
+ }>;
104
+ tools: Record<string, ToolRegistryTool>;
105
+ aliases: Record<string, ToolRegistryAlias>;
106
+ }
107
+ export interface ResolvedAlias extends ToolRegistryAlias {
108
+ name: string;
109
+ }
110
+ /** The alias entry for `name`, or null when `name` is not an alias. */
111
+ export declare function resolveAlias(registry: ToolRegistry, name: string): ResolvedAlias | null;
112
+ /**
113
+ * Translates an alias call's arguments into the target tool's arguments.
114
+ * Always returns a fresh object (never mutates the caller's args): renames
115
+ * first, then injected params, which win over anything the caller passed.
116
+ */
117
+ export declare function translateArgs(alias: ToolRegistryAlias, args: unknown): Record<string, unknown>;
118
+ export type ValidateModeResult = {
119
+ ok: true;
120
+ mode: string | null;
121
+ args: Record<string, unknown>;
122
+ } | {
123
+ ok: false;
124
+ error: string;
125
+ };
126
+ /**
127
+ * The mode a param-driven tool (selector "params") runs in for these args:
128
+ * the first mode whose `when` params are present, otherwise the tool's
129
+ * default mode (the one without `when`). Undefined for other tools.
130
+ */
131
+ export declare function detectParamsMode(tool: ToolRegistryTool, args: unknown): string | undefined;
132
+ /**
133
+ * Validates and normalises a call's arguments against the registry's per-mode
134
+ * rules, BEFORE any request is made. It is the normaliser on both surfaces
135
+ * (the hosted endpoint has no zod), so a preview call and its confirm call
136
+ * hash identically: numeric strings become numbers, defaults are applied, and
137
+ * params outside the selected mode are rejected with a plain error.
138
+ *
139
+ * `explicitMode` forces a mode for param-driven tools (selector "params"), for
140
+ * example an alias of the old get_comment tool always runs in the comment
141
+ * mode. Without it, a param-driven tool's mode is detected from which params
142
+ * are present (see detectParamsMode).
143
+ *
144
+ * Tools without views/actions, and modes without a `params` spec, pass
145
+ * through unchanged (a fresh copy).
146
+ */
147
+ export declare function validateMode(registry: ToolRegistry, toolName: string, args: unknown, explicitMode?: string): ValidateModeResult;
148
+ /**
149
+ * The canonical form of a call's arguments for hashing: `confirm` and
150
+ * `preview_id` removed, undefined dropped, object keys sorted recursively,
151
+ * arrays kept in order. Pass args AFTER validateMode so defaults and number
152
+ * coercion are already applied.
153
+ */
154
+ export declare function canonicalArgs(args: unknown): Record<string, unknown>;
155
+ export interface DeprecationInfo {
156
+ old: string;
157
+ new: string;
158
+ action: string | null;
159
+ sunset: string;
160
+ }
161
+ /**
162
+ * The note appended (as a final text content item, never touching content[0])
163
+ * to every alias call's result, plus the matching _meta payload. `action` in
164
+ * the payload is the injected view/action/type value (null when none).
165
+ */
166
+ export declare function deprecationNote(alias: ResolvedAlias): {
167
+ text: string;
168
+ meta: DeprecationInfo;
169
+ };
170
+ export declare const DEPRECATION_META_KEY = "posterly/deprecation";
171
+ export interface ParsedToolsets {
172
+ /** Enabled set names, or every set when "all" (the default). */
173
+ enabled: ToolsetName[];
174
+ /** Requested names that are not known sets (ignored). */
175
+ unknown: string[];
176
+ /** True when every set is enabled. */
177
+ all: boolean;
178
+ }
179
+ /**
180
+ * Parses a toolset selection such as "core,inbox" or "all". Empty, missing,
181
+ * or all-unknown input means every set (nobody loses tools by mistake).
182
+ * With a surface, sets not available on it (for example signup, stdio only,
183
+ * on the hosted endpoint) are treated as unknown.
184
+ */
185
+ export declare function parseToolsets(registry: ToolRegistry, value: string | null | undefined, surface?: ToolSurface): ParsedToolsets;
186
+ /**
187
+ * Names of the canonical tools visible on `surface` for the enabled sets.
188
+ * Aliases are never listed. Sets marked alwaysOn (signup on stdio) are always
189
+ * visible. Surfaces keep their own registration order by filtering with this.
190
+ */
191
+ export declare function visibleTools(registry: ToolRegistry, sets: ToolsetName[], surface: ToolSurface): Set<string>;
192
+ export interface DerivedAnnotations {
193
+ readOnlyHint: boolean;
194
+ destructiveHint: boolean;
195
+ idempotentHint: boolean;
196
+ openWorldHint: boolean;
197
+ }
198
+ /**
199
+ * Annotation hints derived from the registry: a multi-action tool is
200
+ * destructive if any action is, idempotent only if all are, openWorld if any
201
+ * is; multi-view reads are readOnly + idempotent, openWorld if any view is.
202
+ */
203
+ export declare function deriveAnnotations(tool: ToolRegistryTool): DerivedAnnotations;
204
+ /** Actions (sub tools) a tool counts for: its views/actions, otherwise 1. */
205
+ export declare function countActions(tool: ToolRegistryTool): number;
206
+ export interface ToolListingAction {
207
+ key: string;
208
+ label: string;
209
+ }
210
+ export interface ToolListingTool {
211
+ name: string;
212
+ label: string;
213
+ /** The view/action/type param name, or null for param-driven or single-mode tools. */
214
+ selector: string | null;
215
+ /** Views/actions (the "sub tools") with plain-English labels; empty for single-mode tools. */
216
+ actions: ToolListingAction[];
217
+ }
218
+ export interface ToolListingSet {
219
+ set: ToolsetName;
220
+ label: string;
221
+ description: string;
222
+ tools: ToolListingTool[];
223
+ }
224
+ /**
225
+ * Every canonical tool on `surface`, grouped by tool set in registry order,
226
+ * each with its views/actions and their labels. This is what every tool list
227
+ * in the docs, marketing pages, and server card renders from, so the "sub
228
+ * tools" inside a merged tool are always shown. Aliases are never listed.
229
+ */
230
+ export declare function listToolsBySet(registry: ToolRegistry, surface: ToolSurface): ToolListingSet[];
231
+ /**
232
+ * What a called name resolves to: the canonical tool plus the view/action it
233
+ * runs (for an alias), or the name itself. Used by /admin/mcp to show old
234
+ * names next to the tool they now reach, without any new telemetry column.
235
+ */
236
+ export declare function resolveCalledTool(registry: ToolRegistry, calledName: string): {
237
+ called: string;
238
+ tool: string;
239
+ mode: string | null;
240
+ alias: boolean;
241
+ };
242
+ /**
243
+ * The initialize `instructions` text: which tool sets exist, that they are
244
+ * all on by default, how to load fewer, and how preview then confirm works.
245
+ */
246
+ export declare function toolsetInstructions(registry: ToolRegistry, surface: ToolSurface): string;
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Pure, dependency-free helpers over the MCP tool registry
3
+ * (mcp-server/tool-registry.json). Shared by BOTH surfaces:
4
+ * - the npm stdio package (mcp-server/src/index.ts, alias-transport.ts)
5
+ * - the hosted endpoint (lib/mcp/tool-registry.ts re-exports these with the
6
+ * registry bound)
7
+ *
8
+ * This module never imports the JSON itself: each surface loads the registry
9
+ * its own way (createRequire on stdio, a static JSON import on hosted) and
10
+ * passes it in. Keep it free of Node, Next, and zod imports so it compiles
11
+ * unchanged under both the package tsconfig and the app tsconfig.
12
+ */
13
+ /** The alias entry for `name`, or null when `name` is not an alias. */
14
+ export function resolveAlias(registry, name) {
15
+ if (!Object.prototype.hasOwnProperty.call(registry.aliases, name))
16
+ return null;
17
+ return { name, ...registry.aliases[name] };
18
+ }
19
+ function isPlainObject(value) {
20
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
21
+ }
22
+ /**
23
+ * Translates an alias call's arguments into the target tool's arguments.
24
+ * Always returns a fresh object (never mutates the caller's args): renames
25
+ * first, then injected params, which win over anything the caller passed.
26
+ */
27
+ export function translateArgs(alias, args) {
28
+ const source = isPlainObject(args) ? args : {};
29
+ const out = {};
30
+ for (const [key, value] of Object.entries(source)) {
31
+ const renamed = alias.rename && Object.prototype.hasOwnProperty.call(alias.rename, key) ? alias.rename[key] : key;
32
+ out[renamed] = value;
33
+ }
34
+ for (const [key, value] of Object.entries(alias.inject ?? {})) {
35
+ out[key] = value;
36
+ }
37
+ return out;
38
+ }
39
+ const MODE_COMMON_PARAMS = new Set(['confirm', 'preview_id']);
40
+ function modeEntries(tool) {
41
+ return tool.views ?? tool.actions ?? null;
42
+ }
43
+ function normalizeParam(name, value, spec, where) {
44
+ switch (spec.type) {
45
+ case 'integer':
46
+ case 'number': {
47
+ let n = value;
48
+ if (typeof value === 'string' && value.trim() !== '' && /^-?\d+(\.\d+)?$/.test(value.trim()))
49
+ n = Number(value.trim());
50
+ if (typeof n !== 'number' || !Number.isFinite(n))
51
+ return { ok: false, error: `${name} must be a number${where}.` };
52
+ if (spec.type === 'integer' && !Number.isInteger(n))
53
+ return { ok: false, error: `${name} must be a whole number${where}.` };
54
+ if (spec.min != null && n < spec.min)
55
+ return { ok: false, error: `${name} must be at least ${spec.min}${where}.` };
56
+ if (spec.max != null && n > spec.max)
57
+ return { ok: false, error: `${name} must be at most ${spec.max}${where}.` };
58
+ if (spec.enum && !spec.enum.includes(n))
59
+ return { ok: false, error: `${name} must be one of ${spec.enum.join(', ')}${where}.` };
60
+ return { ok: true, value: n };
61
+ }
62
+ case 'string': {
63
+ if (typeof value === 'number' && Number.isFinite(value))
64
+ value = String(value);
65
+ if (typeof value !== 'string')
66
+ return { ok: false, error: `${name} must be a string${where}.` };
67
+ if (spec.enum && !spec.enum.includes(value))
68
+ return { ok: false, error: `${name} must be one of ${spec.enum.join(', ')}${where}.` };
69
+ return { ok: true, value };
70
+ }
71
+ case 'boolean':
72
+ if (typeof value !== 'boolean')
73
+ return { ok: false, error: `${name} must be true or false${where}.` };
74
+ return { ok: true, value };
75
+ case 'array':
76
+ if (!Array.isArray(value))
77
+ return { ok: false, error: `${name} must be a list${where}.` };
78
+ return { ok: true, value };
79
+ case 'object':
80
+ if (!isPlainObject(value))
81
+ return { ok: false, error: `${name} must be an object${where}.` };
82
+ return { ok: true, value };
83
+ default:
84
+ return { ok: true, value };
85
+ }
86
+ }
87
+ function isPresent(value) {
88
+ return value !== undefined && value !== null && value !== '';
89
+ }
90
+ /**
91
+ * The mode a param-driven tool (selector "params") runs in for these args:
92
+ * the first mode whose `when` params are present, otherwise the tool's
93
+ * default mode (the one without `when`). Undefined for other tools.
94
+ */
95
+ export function detectParamsMode(tool, args) {
96
+ if (tool.selector !== 'params')
97
+ return undefined;
98
+ const entries = modeEntries(tool);
99
+ if (!entries)
100
+ return undefined;
101
+ const source = isPlainObject(args) ? args : {};
102
+ for (const [mode, entry] of Object.entries(entries)) {
103
+ if (entry.when?.some((key) => isPresent(source[key])))
104
+ return mode;
105
+ }
106
+ if (tool.defaultMode !== undefined)
107
+ return tool.defaultMode;
108
+ return Object.entries(entries).find(([, entry]) => !entry.when)?.[0];
109
+ }
110
+ /**
111
+ * Validates and normalises a call's arguments against the registry's per-mode
112
+ * rules, BEFORE any request is made. It is the normaliser on both surfaces
113
+ * (the hosted endpoint has no zod), so a preview call and its confirm call
114
+ * hash identically: numeric strings become numbers, defaults are applied, and
115
+ * params outside the selected mode are rejected with a plain error.
116
+ *
117
+ * `explicitMode` forces a mode for param-driven tools (selector "params"), for
118
+ * example an alias of the old get_comment tool always runs in the comment
119
+ * mode. Without it, a param-driven tool's mode is detected from which params
120
+ * are present (see detectParamsMode).
121
+ *
122
+ * Tools without views/actions, and modes without a `params` spec, pass
123
+ * through unchanged (a fresh copy).
124
+ */
125
+ export function validateMode(registry, toolName, args, explicitMode) {
126
+ const tool = registry.tools[toolName];
127
+ const source = isPlainObject(args) ? { ...args } : {};
128
+ if (!tool)
129
+ return { ok: false, error: `Unknown tool: ${toolName}` };
130
+ const entries = modeEntries(tool);
131
+ if (!entries || !tool.selector)
132
+ return { ok: true, mode: null, args: source };
133
+ const selector = tool.selector;
134
+ let mode = explicitMode;
135
+ if (selector === 'params' && mode === undefined) {
136
+ mode = detectParamsMode(tool, source);
137
+ }
138
+ else if (selector !== 'params') {
139
+ const raw = source[selector];
140
+ if (raw === undefined || raw === null || raw === '') {
141
+ mode = tool.defaultMode;
142
+ if (mode === undefined) {
143
+ return { ok: false, error: `${selector} is required. Use one of: ${Object.keys(entries).join(', ')}.` };
144
+ }
145
+ source[selector] = mode;
146
+ }
147
+ else if (typeof raw !== 'string' || !Object.prototype.hasOwnProperty.call(entries, raw)) {
148
+ return { ok: false, error: `${selector} must be one of: ${Object.keys(entries).join(', ')}.` };
149
+ }
150
+ else {
151
+ mode = raw;
152
+ }
153
+ }
154
+ if (mode === undefined)
155
+ return { ok: true, mode: null, args: source };
156
+ const entry = entries[mode];
157
+ if (!entry)
158
+ return { ok: false, error: `Unknown ${selector === 'params' ? 'mode' : selector} ${mode} for ${toolName}.` };
159
+ if (!entry.params)
160
+ return { ok: true, mode, args: source };
161
+ const where = selector === 'params' ? '' : ` with ${selector}=${mode}`;
162
+ const notAllowedWhere = selector === 'params'
163
+ ? (entry.when?.length ? ` together with ${entry.when.join(' or ')}` : '')
164
+ : where;
165
+ for (const key of Object.keys(source)) {
166
+ if (key === selector || MODE_COMMON_PARAMS.has(key))
167
+ continue;
168
+ if (!Object.prototype.hasOwnProperty.call(entry.params, key)) {
169
+ // Many clients send every optional field, unset ones as null or "".
170
+ // Those carry no value, so they are dropped (never rejected), which
171
+ // also keeps a preview call and its confirm call hashing identically.
172
+ if (!isPresent(source[key])) {
173
+ delete source[key];
174
+ continue;
175
+ }
176
+ return { ok: false, error: `${key} is not allowed${notAllowedWhere}.` };
177
+ }
178
+ }
179
+ for (const [name, spec] of Object.entries(entry.params)) {
180
+ // The old hosted tools skipped falsy values (`if (input?.limit)`), so an
181
+ // empty string for a non-string param still means "not given".
182
+ if (source[name] === '' && spec.type && spec.type !== 'string')
183
+ delete source[name];
184
+ const value = source[name];
185
+ if (value === null && spec.nullable)
186
+ continue;
187
+ if (value === undefined || value === null) {
188
+ if (spec.required)
189
+ return { ok: false, error: `${name} is required${where}.` };
190
+ if (spec.default !== undefined)
191
+ source[name] = spec.default;
192
+ else
193
+ delete source[name];
194
+ continue;
195
+ }
196
+ const normalized = normalizeParam(name, value, spec, where);
197
+ if (!normalized.ok)
198
+ return normalized;
199
+ source[name] = normalized.value;
200
+ }
201
+ return { ok: true, mode, args: source };
202
+ }
203
+ function sortKeysDeep(value) {
204
+ if (Array.isArray(value))
205
+ return value.map((item) => (item === undefined ? null : sortKeysDeep(item)));
206
+ if (isPlainObject(value)) {
207
+ const out = {};
208
+ for (const key of Object.keys(value).sort()) {
209
+ const item = value[key];
210
+ if (item === undefined)
211
+ continue;
212
+ out[key] = sortKeysDeep(item);
213
+ }
214
+ return out;
215
+ }
216
+ return value;
217
+ }
218
+ /**
219
+ * The canonical form of a call's arguments for hashing: `confirm` and
220
+ * `preview_id` removed, undefined dropped, object keys sorted recursively,
221
+ * arrays kept in order. Pass args AFTER validateMode so defaults and number
222
+ * coercion are already applied.
223
+ */
224
+ export function canonicalArgs(args) {
225
+ const source = isPlainObject(args) ? args : {};
226
+ const stripped = {};
227
+ for (const [key, value] of Object.entries(source)) {
228
+ if (key === 'confirm' || key === 'preview_id')
229
+ continue;
230
+ stripped[key] = value;
231
+ }
232
+ return sortKeysDeep(stripped);
233
+ }
234
+ function injectedMode(alias) {
235
+ const inject = alias.inject ?? {};
236
+ for (const key of ['action', 'view', 'type']) {
237
+ const value = inject[key];
238
+ if (typeof value === 'string')
239
+ return { key, value };
240
+ }
241
+ return null;
242
+ }
243
+ /**
244
+ * The note appended (as a final text content item, never touching content[0])
245
+ * to every alias call's result, plus the matching _meta payload. `action` in
246
+ * the payload is the injected view/action/type value (null when none).
247
+ */
248
+ export function deprecationNote(alias) {
249
+ const mode = injectedMode(alias);
250
+ const target = mode ? `${alias.target} with ${mode.key}=${mode.value}` : alias.target;
251
+ return {
252
+ text: `Renamed: ${alias.name} is now ${target}. The old name may stop working after ${alias.sunset}.`,
253
+ meta: { old: alias.name, new: alias.target, action: mode ? mode.value : null, sunset: alias.sunset },
254
+ };
255
+ }
256
+ export const DEPRECATION_META_KEY = 'posterly/deprecation';
257
+ /**
258
+ * Parses a toolset selection such as "core,inbox" or "all". Empty, missing,
259
+ * or all-unknown input means every set (nobody loses tools by mistake).
260
+ * With a surface, sets not available on it (for example signup, stdio only,
261
+ * on the hosted endpoint) are treated as unknown.
262
+ */
263
+ export function parseToolsets(registry, value, surface) {
264
+ const available = Object.entries(registry.toolsets)
265
+ .filter(([, set]) => !surface || !set.surfaces || set.surfaces.includes(surface))
266
+ .map(([name]) => name);
267
+ const requested = String(value ?? '')
268
+ .split(',')
269
+ .map((part) => part.trim().toLowerCase())
270
+ .filter(Boolean);
271
+ if (requested.length === 0 || requested.includes('all')) {
272
+ return { enabled: available, unknown: requested.filter((name) => name !== 'all' && !available.includes(name)), all: true };
273
+ }
274
+ const enabled = available.filter((name) => requested.includes(name));
275
+ const unknown = requested.filter((name) => !available.includes(name));
276
+ if (enabled.length === 0)
277
+ return { enabled: available, unknown, all: true };
278
+ return { enabled, unknown, all: enabled.length === available.length };
279
+ }
280
+ /**
281
+ * Names of the canonical tools visible on `surface` for the enabled sets.
282
+ * Aliases are never listed. Sets marked alwaysOn (signup on stdio) are always
283
+ * visible. Surfaces keep their own registration order by filtering with this.
284
+ */
285
+ export function visibleTools(registry, sets, surface) {
286
+ const enabled = new Set(sets);
287
+ const visible = new Set();
288
+ for (const [name, tool] of Object.entries(registry.tools)) {
289
+ const surfaces = tool.surfaces ?? ['hosted', 'stdio'];
290
+ if (!surfaces.includes(surface))
291
+ continue;
292
+ const set = registry.toolsets[tool.set];
293
+ if (enabled.has(tool.set) || set?.alwaysOn)
294
+ visible.add(name);
295
+ }
296
+ return visible;
297
+ }
298
+ /**
299
+ * Annotation hints derived from the registry: a multi-action tool is
300
+ * destructive if any action is, idempotent only if all are, openWorld if any
301
+ * is; multi-view reads are readOnly + idempotent, openWorld if any view is.
302
+ */
303
+ export function deriveAnnotations(tool) {
304
+ if (tool.views && !tool.actions) {
305
+ const views = Object.values(tool.views);
306
+ return {
307
+ readOnlyHint: true,
308
+ destructiveHint: false,
309
+ idempotentHint: true,
310
+ openWorldHint: views.some((view) => view.openWorld === true),
311
+ };
312
+ }
313
+ if (tool.actions) {
314
+ const actions = Object.values(tool.actions);
315
+ return {
316
+ readOnlyHint: false,
317
+ destructiveHint: actions.some((action) => action.destructive === true),
318
+ idempotentHint: actions.length > 0 && actions.every((action) => action.idempotent === true),
319
+ openWorldHint: actions.some((action) => action.openWorld === true),
320
+ };
321
+ }
322
+ const readOnly = tool.readOnly === true;
323
+ return {
324
+ readOnlyHint: readOnly,
325
+ destructiveHint: !readOnly && tool.destructive === true,
326
+ idempotentHint: readOnly || tool.idempotent === true,
327
+ openWorldHint: tool.openWorld === true,
328
+ };
329
+ }
330
+ /** Actions (sub tools) a tool counts for: its views/actions, otherwise 1. */
331
+ export function countActions(tool) {
332
+ const entries = modeEntries(tool);
333
+ return entries ? Math.max(1, Object.keys(entries).length) : 1;
334
+ }
335
+ /**
336
+ * Every canonical tool on `surface`, grouped by tool set in registry order,
337
+ * each with its views/actions and their labels. This is what every tool list
338
+ * in the docs, marketing pages, and server card renders from, so the "sub
339
+ * tools" inside a merged tool are always shown. Aliases are never listed.
340
+ */
341
+ export function listToolsBySet(registry, surface) {
342
+ const groups = [];
343
+ for (const [set, info] of Object.entries(registry.toolsets)) {
344
+ if (info.surfaces && !info.surfaces.includes(surface))
345
+ continue;
346
+ const tools = [];
347
+ for (const [name, tool] of Object.entries(registry.tools)) {
348
+ if (tool.set !== set)
349
+ continue;
350
+ if (!(tool.surfaces ?? ['hosted', 'stdio']).includes(surface))
351
+ continue;
352
+ const entries = modeEntries(tool);
353
+ tools.push({
354
+ name,
355
+ label: tool.label,
356
+ selector: entries && tool.selector && tool.selector !== 'params' ? tool.selector : null,
357
+ actions: entries ? Object.entries(entries).map(([key, entry]) => ({ key, label: entry.label })) : [],
358
+ });
359
+ }
360
+ if (tools.length > 0)
361
+ groups.push({ set, label: info.label, description: info.description, tools });
362
+ }
363
+ return groups;
364
+ }
365
+ /**
366
+ * What a called name resolves to: the canonical tool plus the view/action it
367
+ * runs (for an alias), or the name itself. Used by /admin/mcp to show old
368
+ * names next to the tool they now reach, without any new telemetry column.
369
+ */
370
+ export function resolveCalledTool(registry, calledName) {
371
+ const alias = resolveAlias(registry, calledName);
372
+ if (!alias)
373
+ return { called: calledName, tool: calledName, mode: null, alias: false };
374
+ const injected = injectedMode(alias);
375
+ return { called: calledName, tool: alias.target, mode: injected?.value ?? alias.mode ?? null, alias: true };
376
+ }
377
+ /**
378
+ * The initialize `instructions` text: which tool sets exist, that they are
379
+ * all on by default, how to load fewer, and how preview then confirm works.
380
+ */
381
+ export function toolsetInstructions(registry, surface) {
382
+ const sets = Object.entries(registry.toolsets)
383
+ .filter(([, set]) => !set.surfaces || set.surfaces.includes(surface))
384
+ .map(([name, set]) => `${name} (${set.description.split('. ')[0].replace(/\.$/, '')})`);
385
+ const howTo = surface === 'hosted'
386
+ ? 'To load fewer tools with an API key in the Authorization header, add ?toolsets=core,inbox to the endpoint URL. OAuth connectors always get every set.'
387
+ : 'To load fewer tools, set POSTERLY_TOOLSETS=core,inbox (or pass --toolsets=core,inbox). The signup tools are always on.';
388
+ return [
389
+ `posterly groups its tools into sets: ${sets.join('; ')}.`,
390
+ `Every set is on by default. ${howTo} Sets only change which tools are listed; any tool can still be called by name.`,
391
+ 'Merged tools pick what to do with a view, action, or type param; each tool description names every option.',
392
+ 'Tools that post publicly or delete things use preview then confirm: call once without confirm to get a preview and a preview_id, show it to the user, then call again with confirm: true and that preview_id.',
393
+ ].join(' ');
394
+ }