salesforce-reports-mcp 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +87 -105
- package/dist/dashboard-files.js +136 -0
- package/dist/http-auth.js +310 -0
- package/dist/http.js +94 -0
- package/dist/index.js +59 -3
- package/dist/reports/api.js +19 -0
- package/dist/reports/dashboards.js +308 -0
- package/dist/server.js +210 -3
- package/dist/widget/dashboard.html +946 -0
- package/dist/widget/report.html +722 -63
- package/dist/widget/view.js +32 -10
- package/package.json +6 -1
- package/skills/report-designer/transport.md +6 -2
- package/skills/report-runner/SKILL.md +20 -1
- package/skills/report-runner/dashboard-loader.js +76 -0
- package/skills/report-runner/reference.md +36 -0
- package/skills/report-runner/transport.md +6 -2
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { InputError } from "../format.js";
|
|
2
|
+
import { SalesforceError } from "../salesforce/client.js";
|
|
3
|
+
import { soqlLike } from "./api.js";
|
|
4
|
+
import { shapeResult } from "./shape.js";
|
|
5
|
+
import { humanize, reportUrl } from "./summarize.js";
|
|
6
|
+
/** Seconds between status polls after a refresh, and how many polls: 20 polls 3 seconds apart is 60 seconds. */
|
|
7
|
+
export const REFRESH_POLL_MS = 3000;
|
|
8
|
+
export const REFRESH_POLLS = 20;
|
|
9
|
+
/** Default cap on detail rows per component. */
|
|
10
|
+
export const COMPONENT_ROWS = 20;
|
|
11
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
12
|
+
export function dashboardUrl(baseUrl, id) {
|
|
13
|
+
return baseUrl && id ? `${baseUrl}/lightning/r/Dashboard/${id}/view` : undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* SOQL on Dashboard. GET /analytics/dashboards lists only recently viewed dashboards, so listing goes through SOQL,
|
|
17
|
+
* which returns the dashboards the signed-in user can see. One row past the limit tells whether the list was cut.
|
|
18
|
+
*/
|
|
19
|
+
export function dashboardListSoql(input) {
|
|
20
|
+
const where = [];
|
|
21
|
+
if (input.query)
|
|
22
|
+
where.push(`(Title LIKE '%${soqlLike(input.query)}%' OR DeveloperName LIKE '%${soqlLike(input.query)}%')`);
|
|
23
|
+
if (input.folder)
|
|
24
|
+
where.push(`FolderName LIKE '%${soqlLike(input.folder)}%'`);
|
|
25
|
+
return `SELECT Id, Title, DeveloperName, FolderName, FolderId, Description, Type, LastModifiedDate FROM Dashboard${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY LastModifiedDate DESC LIMIT ${input.limit + 1}`;
|
|
26
|
+
}
|
|
27
|
+
/** The newest refresh date in a status answer, or null when no component was ever refreshed. */
|
|
28
|
+
export function latestRefresh(status) {
|
|
29
|
+
const dates = (status?.componentStatus ?? []).map((c) => c.refreshDate).filter((d) => Boolean(d));
|
|
30
|
+
if (!dates.length)
|
|
31
|
+
return null;
|
|
32
|
+
return dates.reduce((a, b) => (time(b) > time(a) ? b : a));
|
|
33
|
+
}
|
|
34
|
+
export function optionLabel(option) {
|
|
35
|
+
if (option.alias)
|
|
36
|
+
return String(option.alias);
|
|
37
|
+
if (option.value !== null && option.value !== undefined && option.value !== "")
|
|
38
|
+
return String(option.value);
|
|
39
|
+
const start = option.startValue;
|
|
40
|
+
const end = option.endValue;
|
|
41
|
+
if (start && end)
|
|
42
|
+
return `${start} to ${end}`;
|
|
43
|
+
if (start)
|
|
44
|
+
return `${start} or more`;
|
|
45
|
+
if (end)
|
|
46
|
+
return `up to ${end}`;
|
|
47
|
+
return String(option.id);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Filter choices by name and option label, mapped to the option ids the data calls take. Salesforce reads the
|
|
51
|
+
* option id from `filter<n>` on the query string, n being the filter's place in describe's `filters` (only
|
|
52
|
+
* filter1 was proven, on a one-filter dashboard). The option text itself is refused with 400, so it is never sent.
|
|
53
|
+
*/
|
|
54
|
+
export function resolveFilters(meta, choices) {
|
|
55
|
+
const filters = (meta.filters ?? []);
|
|
56
|
+
const all = (f) => `${f.name}: all (no option chosen)`;
|
|
57
|
+
if (!choices?.length)
|
|
58
|
+
return { query: "", words: filters.map(all), applied: [] };
|
|
59
|
+
const listing = () => filters.map((f) => `${f.name} (${(f.options ?? []).map(optionLabel).join(", ")})`).join("; ");
|
|
60
|
+
if (!filters.length)
|
|
61
|
+
throw new InputError("This dashboard has no filters. Leave out `filters`.");
|
|
62
|
+
const chosen = new Map();
|
|
63
|
+
for (const choice of choices) {
|
|
64
|
+
const index = filters.findIndex((f) => same(f.name, choice.name));
|
|
65
|
+
if (index < 0)
|
|
66
|
+
throw new InputError(`No dashboard filter named "${choice.name}". This dashboard's filters: ${listing()}.`);
|
|
67
|
+
const filter = filters[index];
|
|
68
|
+
if (chosen.has(index))
|
|
69
|
+
throw new InputError(`The filter ${filter.name} is given twice. Give one option per filter.`);
|
|
70
|
+
const options = (filter.options ?? []);
|
|
71
|
+
const option = options.find((o) => o.id === choice.option || same(optionLabel(o), choice.option) || same(o.value, choice.option) || same(o.alias, choice.option));
|
|
72
|
+
if (!option)
|
|
73
|
+
throw new InputError(`${filter.name} has no option "${choice.option}". Its options: ${options.map(optionLabel).join(", ")}.`);
|
|
74
|
+
chosen.set(index, option);
|
|
75
|
+
}
|
|
76
|
+
const query = `?${[...chosen.entries()]
|
|
77
|
+
.sort(([a], [b]) => a - b)
|
|
78
|
+
.map(([i, o]) => `filter${i + 1}=${encodeURIComponent(String(o.id))}`)
|
|
79
|
+
.join("&")}`;
|
|
80
|
+
const words = filters.map((f, i) => (chosen.has(i) ? `${f.name}: ${optionLabel(chosen.get(i))}` : all(f)));
|
|
81
|
+
return { query, words, applied: words.filter((_, i) => chosen.has(i)) };
|
|
82
|
+
}
|
|
83
|
+
/** Whose data the dashboard shows, in words. */
|
|
84
|
+
export function runningUserWords(meta) {
|
|
85
|
+
const name = meta.runningUser?.displayName;
|
|
86
|
+
switch (meta.dashboardType) {
|
|
87
|
+
case "SpecifiedUser":
|
|
88
|
+
return `${name ?? "A set user"}: the dashboard always runs as this user, so every viewer sees the same data.`;
|
|
89
|
+
case "LoggedInUser":
|
|
90
|
+
return "The viewer: each person sees the data they can see, so these results are the signed-in user's.";
|
|
91
|
+
case "MyTeamUser":
|
|
92
|
+
return "The viewer, who as a manager can also view it as someone on their team. These results are the signed-in user's.";
|
|
93
|
+
default:
|
|
94
|
+
return name ? `${name} (${meta.dashboardType ?? "unknown type"})` : "Unknown";
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** describe's components in layout order (top to bottom, then left to right), each with its grid position. */
|
|
98
|
+
function inLayoutOrder(meta) {
|
|
99
|
+
const components = (meta.components ?? []);
|
|
100
|
+
const cells = (meta.layout?.components ?? []);
|
|
101
|
+
const placed = components.map((component, i) => {
|
|
102
|
+
const cell = cells[i];
|
|
103
|
+
const position = cell ? { row: cell.row, column: cell.column, rows: cell.rowspan, columns: cell.colspan } : null;
|
|
104
|
+
return { component, position, i };
|
|
105
|
+
});
|
|
106
|
+
placed.sort((a, b) => {
|
|
107
|
+
if (!a.position || !b.position)
|
|
108
|
+
return a.i - b.i;
|
|
109
|
+
return a.position.row - b.position.row || a.position.column - b.position.column || a.i - b.i;
|
|
110
|
+
});
|
|
111
|
+
return placed.map(({ component, position }) => ({ component, position }));
|
|
112
|
+
}
|
|
113
|
+
const AGGREGATE_WORDS = { s: "Sum of", a: "Average of", m: "Smallest", mx: "Largest", u: "Unique" };
|
|
114
|
+
function measureLabel(name) {
|
|
115
|
+
if (name === "RowCount")
|
|
116
|
+
return "Record Count";
|
|
117
|
+
const prefix = /^([a-z]+)!/.exec(name)?.[1];
|
|
118
|
+
const words = prefix ? AGGREGATE_WORDS[prefix] : undefined;
|
|
119
|
+
return words ? `${words} ${humanize(name)}` : humanize(name);
|
|
120
|
+
}
|
|
121
|
+
export function summarizeDashboard(describe, options) {
|
|
122
|
+
const names = options.reportNames ?? new Map();
|
|
123
|
+
const nameOf = (id) => (id ? (names.get(id) ?? names.get(id.slice(0, 15)) ?? null) : null);
|
|
124
|
+
return {
|
|
125
|
+
id: describe.id,
|
|
126
|
+
name: describe.name,
|
|
127
|
+
developerName: describe.developerName ?? null,
|
|
128
|
+
description: describe.description ?? null,
|
|
129
|
+
folder: { id: describe.folderId ?? null, name: describe.folderName ?? null },
|
|
130
|
+
type: describe.dashboardType ?? null,
|
|
131
|
+
runningUser: runningUserWords(describe),
|
|
132
|
+
owner: describe.owner?.displayName ?? null,
|
|
133
|
+
url: dashboardUrl(options.baseUrl, describe.id),
|
|
134
|
+
filters: (describe.filters ?? []).map((f) => ({
|
|
135
|
+
name: f.name,
|
|
136
|
+
dataType: f.dataType ?? null,
|
|
137
|
+
options: (f.options ?? []).map(optionLabel),
|
|
138
|
+
})),
|
|
139
|
+
layout: `Components are listed in layout order: top to bottom, then left to right, on a grid ${describe.layout?.numColumns ?? 12} columns wide.`,
|
|
140
|
+
components: inLayoutOrder(describe).map(({ component: c, position }) => {
|
|
141
|
+
const props = c.properties ?? {};
|
|
142
|
+
const reportId = c.reportId ?? null;
|
|
143
|
+
return {
|
|
144
|
+
id: c.id,
|
|
145
|
+
header: c.header ?? null,
|
|
146
|
+
title: c.title ?? null,
|
|
147
|
+
footer: c.footer ?? null,
|
|
148
|
+
visualizationType: props.visualizationType ?? null,
|
|
149
|
+
report: { id: reportId, name: nameOf(reportId), url: reportUrl(options.baseUrl, reportId) },
|
|
150
|
+
groupings: (props.groupings ?? []).map((g) => g.name),
|
|
151
|
+
measures: (props.aggregates ?? []).map((a) => ({ name: a.name, label: measureLabel(a.name) })),
|
|
152
|
+
position,
|
|
153
|
+
};
|
|
154
|
+
}),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/** GET /analytics/dashboards/{id} to a DashboardResult. Each component's reportResult is shaped by shapeResult. */
|
|
158
|
+
export function shapeDashboard(results, options) {
|
|
159
|
+
const meta = results.dashboardMetadata ?? {};
|
|
160
|
+
const applied = options.appliedFilters ?? [];
|
|
161
|
+
const data = new Map((results.componentData ?? []).map((d) => [d.componentId, d]));
|
|
162
|
+
const notes = [];
|
|
163
|
+
const id = meta.id ?? results.attributes?.dashboardId;
|
|
164
|
+
const components = inLayoutOrder(meta).map(({ component: c }) => {
|
|
165
|
+
const entry = data.get(c.id);
|
|
166
|
+
const status = entry?.status ?? {};
|
|
167
|
+
const props = c.properties ?? {};
|
|
168
|
+
const out = {
|
|
169
|
+
id: c.id,
|
|
170
|
+
header: c.header ?? null,
|
|
171
|
+
title: c.title ?? null,
|
|
172
|
+
footer: c.footer ?? null,
|
|
173
|
+
visualizationType: props.visualizationType ?? null,
|
|
174
|
+
status: componentStatus(entry),
|
|
175
|
+
refreshedAt: status.refreshDate ?? null,
|
|
176
|
+
};
|
|
177
|
+
if (out.status === "error") {
|
|
178
|
+
out.error = { code: String(status.errorCode ?? status.componentDataStatus ?? "UNKNOWN"), message: String(status.errorMessage ?? "Salesforce gave no message.") };
|
|
179
|
+
}
|
|
180
|
+
if (out.status === "data") {
|
|
181
|
+
const raw = entry.reportResult;
|
|
182
|
+
const result = shapeResult(raw, {
|
|
183
|
+
maxRows: options.maxRows,
|
|
184
|
+
includeDetail: raw.reportMetadata?.reportFormat === "TABULAR",
|
|
185
|
+
baseUrl: options.baseUrl,
|
|
186
|
+
});
|
|
187
|
+
// reportMetadata shows the source report's own filters, never the dashboard's.
|
|
188
|
+
if ((props.filterColumns ?? []).length)
|
|
189
|
+
result.filters.push(...applied.map((w) => `Dashboard filter ${w}`));
|
|
190
|
+
out.result = result;
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
});
|
|
194
|
+
const label = (c) => c.header ?? c.title ?? c.id;
|
|
195
|
+
const withData = components.filter((c) => c.status === "data");
|
|
196
|
+
const noData = components.filter((c) => c.status === "no data");
|
|
197
|
+
const forWhat = applied.length ? ` for ${applied.join(", ")}` : "";
|
|
198
|
+
if (components.length && noData.length === components.length) {
|
|
199
|
+
notes.push(`No component has data${forWhat}: the dashboard has not been refreshed${forWhat ? " with these filters" : ""}. Call refresh_dashboard with the same filters to get numbers.`);
|
|
200
|
+
}
|
|
201
|
+
else if (noData.length) {
|
|
202
|
+
notes.push(`${noData.length} of ${components.length} components have no data${forWhat} (${noData.map(label).join(", ")}). Call refresh_dashboard with the same filters to fill them.`);
|
|
203
|
+
}
|
|
204
|
+
for (const c of components.filter((x) => x.status === "error"))
|
|
205
|
+
notes.push(`${label(c)} failed in Salesforce: ${c.error.code}: ${c.error.message}`);
|
|
206
|
+
const dates = withData.map((c) => c.refreshedAt).filter((d) => Boolean(d));
|
|
207
|
+
const refreshedAt = dates.length ? dates.reduce((a, b) => (time(b) < time(a) ? b : a)) : null;
|
|
208
|
+
if (refreshedAt && withData.some((c) => data.get(c.id)?.status?.refreshStatus === "STALE")) {
|
|
209
|
+
notes.push(`Salesforce marks this data stale: the dashboard was refreshed since with other filters. These numbers are from ${refreshedAt}; call refresh_dashboard with the same filters for current ones.`);
|
|
210
|
+
}
|
|
211
|
+
if (refreshedAt) {
|
|
212
|
+
const age = options.now.getTime() - time(refreshedAt);
|
|
213
|
+
if (age > DAY_MS) {
|
|
214
|
+
const days = Math.floor(age / DAY_MS);
|
|
215
|
+
notes.push(`These numbers were refreshed ${days} day${days === 1 ? "" : "s"} ago, at ${refreshedAt}. Call refresh_dashboard for current ones.`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
for (const c of withData)
|
|
219
|
+
for (const n of c.result.notes)
|
|
220
|
+
notes.push(`${label(c)}: ${n}`);
|
|
221
|
+
return {
|
|
222
|
+
dashboard: {
|
|
223
|
+
id,
|
|
224
|
+
name: meta.name ?? results.attributes?.dashboardName ?? "Dashboard",
|
|
225
|
+
developerName: meta.developerName ?? null,
|
|
226
|
+
folder: { id: meta.folderId ?? null, name: meta.folderName ?? null },
|
|
227
|
+
url: dashboardUrl(options.baseUrl, id),
|
|
228
|
+
},
|
|
229
|
+
runningUser: runningUserWords(meta),
|
|
230
|
+
filters: options.filterWords,
|
|
231
|
+
refreshedAt,
|
|
232
|
+
components,
|
|
233
|
+
notes,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function componentStatus(entry) {
|
|
237
|
+
const status = entry?.status ?? {};
|
|
238
|
+
if (status.errorCode || status.componentDataStatus === "ERROR")
|
|
239
|
+
return "error";
|
|
240
|
+
if (entry?.reportResult)
|
|
241
|
+
return "data";
|
|
242
|
+
if (!entry || status.componentDataStatus === "NO_DATA" || status.componentDataStatus === "DATA")
|
|
243
|
+
return "no data";
|
|
244
|
+
return "error";
|
|
245
|
+
}
|
|
246
|
+
/** The once-a-minute refusal: 403 FORBIDDEN, "You can't refresh this dashboard more than once in a minute." */
|
|
247
|
+
export function isRefreshLimit(error) {
|
|
248
|
+
return error instanceof SalesforceError && error.status === 403 && (error.code === "FORBIDDEN" || /minute/i.test(error.message));
|
|
249
|
+
}
|
|
250
|
+
/** A component is done when it is not running and has an error, or data newer than before the refresh. */
|
|
251
|
+
export function refreshDone(status, before) {
|
|
252
|
+
return (status.componentStatus ?? []).every((c) => {
|
|
253
|
+
if (c.refreshStatus === "RUNNING")
|
|
254
|
+
return false;
|
|
255
|
+
if (c.errorCode || c.componentDataStatus === "ERROR")
|
|
256
|
+
return true;
|
|
257
|
+
return c.componentDataStatus === "DATA" && Boolean(c.refreshDate) && c.refreshDate !== before.get(c.componentId);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Starts a refresh and waits for it: PUT with the filters on the query string (a body is ignored), then the
|
|
262
|
+
* status every 3 seconds until every component is done or 60 seconds pass. Returns notes for the result.
|
|
263
|
+
* The once-a-minute 403 becomes a note; any other failure is thrown.
|
|
264
|
+
*/
|
|
265
|
+
export async function refreshAndWait(reports, id, filters, now) {
|
|
266
|
+
const before = new Map();
|
|
267
|
+
try {
|
|
268
|
+
for (const c of ((await reports.dashboardStatus(id, filters)).componentStatus ?? []))
|
|
269
|
+
before.set(c.componentId, c.refreshDate ?? null);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
/* without the earlier dates, any data counts as new */
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
await reports.refreshDashboard(id, filters);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (!isRefreshLimit(error))
|
|
279
|
+
throw error;
|
|
280
|
+
// A minute after this filter's last refresh when that is still ahead, else a minute from now (the last refresh
|
|
281
|
+
// may have been for other filters, which this status does not show).
|
|
282
|
+
const last = [...before.values()].filter((d) => Boolean(d)).map(time).reduce((a, b) => Math.max(a, b), 0);
|
|
283
|
+
const nowMs = now().getTime();
|
|
284
|
+
const retry = last + 60_000 > nowMs ? last + 60_000 : nowMs + 60_000;
|
|
285
|
+
const after = new Date(retry).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
286
|
+
return [
|
|
287
|
+
`Salesforce refreshes a dashboard at most once a minute, and this one was refreshed less than a minute ago, so these are the cached results. Try again after ${after}.`,
|
|
288
|
+
];
|
|
289
|
+
}
|
|
290
|
+
for (let poll = 0; poll < REFRESH_POLLS; poll++) {
|
|
291
|
+
await reports.pause(REFRESH_POLL_MS);
|
|
292
|
+
try {
|
|
293
|
+
if (refreshDone(await reports.dashboardStatus(id, filters), before))
|
|
294
|
+
return [];
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
/* a failed poll is retried at the next one */
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return [`The refresh had not finished after ${(REFRESH_POLL_MS * REFRESH_POLLS) / 1000} seconds, so some components may show older data. Call run_dashboard in a minute to read the refreshed results.`];
|
|
301
|
+
}
|
|
302
|
+
function same(a, b) {
|
|
303
|
+
return typeof a === "string" && typeof b === "string" && a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
304
|
+
}
|
|
305
|
+
/** Salesforce dates end in "+0000", which is not ISO 8601; add the colon before parsing. */
|
|
306
|
+
function time(date) {
|
|
307
|
+
return Date.parse(date.replace(/([+-]\d{2})(\d{2})$/, "$1:$2"));
|
|
308
|
+
}
|
package/dist/server.js
CHANGED
|
@@ -4,19 +4,88 @@ import { z } from "zod";
|
|
|
4
4
|
import { fail, InputError, ok, okView } from "./format.js";
|
|
5
5
|
import { soqlLike, soqlString } from "./reports/api.js";
|
|
6
6
|
import { combineResults } from "./reports/combine.js";
|
|
7
|
+
import { COMPONENT_ROWS, dashboardListSoql, dashboardUrl, latestRefresh, refreshAndWait, resolveFilters, shapeDashboard, summarizeDashboard, } from "./reports/dashboards.js";
|
|
7
8
|
import { aggregateColumns, definitionShape, ReportDefinitionSchema, toReportMetadata } from "./reports/definition.js";
|
|
8
9
|
import { HARD_ROW_CEILING, shapeResult } from "./reports/shape.js";
|
|
9
10
|
import { reportUrl, standardFilterNotes, summarizeReport, summarizeReportType, summarizeReportTypes } from "./reports/summarize.js";
|
|
10
|
-
import { REPORT_VIEW_URI, reportViewHtml } from "./widget/view.js";
|
|
11
|
+
import { DASHBOARD_VIEW_URI, dashboardViewHtml, REPORT_VIEW_URI, reportViewHtml } from "./widget/view.js";
|
|
11
12
|
/**
|
|
12
13
|
* The last sentence of the run_report and query_report descriptions on the local door, where a host may draw
|
|
13
14
|
* the report view. The hosted door draws no card, so doorDescription (salesforce/scripts/door-tools.ts) strips it.
|
|
14
15
|
*/
|
|
15
|
-
export const VIEW_HINT = " Hosts that draw MCP Apps, such as Claude Desktop, show this result as a report card above your reply
|
|
16
|
+
export const VIEW_HINT = " Hosts that draw MCP Apps, such as Claude Desktop, show this result as a report card above your reply. There, lead with the one finding the card cannot show (concentration, change, risk, the next question), keep the reply short, and never repeat the card's rows, totals or a table.";
|
|
17
|
+
/**
|
|
18
|
+
* The last sentence of the run_dashboard and refresh_dashboard descriptions, where a host may draw the dashboard
|
|
19
|
+
* card. The dashboard tools are on the local door only, so no door strips it.
|
|
20
|
+
*/
|
|
21
|
+
export const DASHBOARD_VIEW_HINT = " Hosts that draw MCP Apps, such as Claude Desktop, show this result as a dashboard card above your reply, with every component drawn as its chart. There, lead with the one finding the card cannot show (what moved, what is missing or stale, a risk, the next question), keep the reply short, and never repeat the card's numbers, components or a table.";
|
|
22
|
+
/**
|
|
23
|
+
* Add to each shaped component what the raw dashboard carries and the card needs: the source report, the first
|
|
24
|
+
* measure's label and type (a metric or gauge result has no groups to carry them), a metric's label and a gauge's
|
|
25
|
+
* range. Components are joined by id, never by index.
|
|
26
|
+
*/
|
|
27
|
+
export function dashboardView(raw, shaped, baseUrl) {
|
|
28
|
+
const meta = new Map((raw.dashboardMetadata?.components ?? []).map((c) => [c.id, c]));
|
|
29
|
+
const data = new Map((raw.componentData ?? []).map((d) => [d.componentId, d]));
|
|
30
|
+
const components = shaped.components.map((c) => {
|
|
31
|
+
const m = meta.get(c.id) ?? {};
|
|
32
|
+
const props = m.properties ?? {};
|
|
33
|
+
const visual = props.visualizationProperties ?? {};
|
|
34
|
+
const reportId = m.reportId ?? c.result?.report.id ?? null;
|
|
35
|
+
const name = (props.aggregates ?? [])[0]?.name;
|
|
36
|
+
const info = name ? data.get(c.id)?.reportResult?.reportExtendedMetadata?.aggregateColumnInfo?.[name] : undefined;
|
|
37
|
+
const view = {
|
|
38
|
+
...c,
|
|
39
|
+
sourceReport: { id: reportId, url: reportUrl(baseUrl, reportId) },
|
|
40
|
+
measure: name ? { name, label: info?.label ?? (name === "RowCount" ? "Record Count" : name), dataType: info?.dataType ?? (name === "RowCount" ? "int" : "number") } : null,
|
|
41
|
+
};
|
|
42
|
+
if (typeof visual.metricLabel === "string" && visual.metricLabel)
|
|
43
|
+
view.metricLabel = visual.metricLabel;
|
|
44
|
+
if (typeof visual.colorPalette === "string" && visual.colorPalette)
|
|
45
|
+
view.colorPalette = visual.colorPalette;
|
|
46
|
+
if (c.visualizationType === "Gauge") {
|
|
47
|
+
const breaks = ((visual.breakPoints ?? [])[0]?.breaks ?? []);
|
|
48
|
+
const bounds = breaks.flatMap((b) => [b.lowerBound, b.upperBound]).filter((n) => typeof n === "number");
|
|
49
|
+
if (bounds.length >= 2) {
|
|
50
|
+
const min = Math.min(...bounds);
|
|
51
|
+
const max = Math.max(...bounds);
|
|
52
|
+
const inner = breaks.slice(1).map((b) => b.lowerBound).filter((n) => typeof n === "number" && n > min && n < max);
|
|
53
|
+
const colors = breaks.map((b) => (typeof b.color === "string" && /^[0-9a-f]{6}$/i.test(b.color) ? `#${b.color.toLowerCase()}` : "")).filter(Boolean);
|
|
54
|
+
if (max > min)
|
|
55
|
+
view.gauge = { min, max, breakpoints: inner, colors: colors.length === inner.length + 1 ? colors : [] };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return view;
|
|
59
|
+
});
|
|
60
|
+
const palette = raw.dashboardMetadata?.colorPalette;
|
|
61
|
+
return { ...shaped, components, ...(typeof palette === "string" && palette ? { colorPalette: palette } : {}) };
|
|
62
|
+
}
|
|
16
63
|
const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
|
|
17
64
|
const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
|
|
18
65
|
const DESTRUCTIVE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true };
|
|
19
66
|
const reportId = z.string().regex(/^00O[A-Za-z0-9]{12,15}$/, "A report id starts with 00O.").describe("Report id, 15 or 18 characters starting with 00O. Find one with search_reports.");
|
|
67
|
+
const dashboardId = z
|
|
68
|
+
.string()
|
|
69
|
+
.regex(/^01Z[A-Za-z0-9]{12,15}$/, "A dashboard id starts with 01Z.")
|
|
70
|
+
.describe("Dashboard id, 15 or 18 characters starting with 01Z. Find one with list_dashboards.");
|
|
71
|
+
const dashboardInputs = {
|
|
72
|
+
dashboardId,
|
|
73
|
+
filters: z
|
|
74
|
+
.array(z.object({
|
|
75
|
+
name: z.string().min(1).describe('The dashboard filter\'s name, as describe_dashboard lists it, for example "Stage".'),
|
|
76
|
+
option: z.string().min(1).describe('One of that filter\'s option labels, for example "Prospecting". An option id (0IC...) works too.'),
|
|
77
|
+
}))
|
|
78
|
+
.max(3)
|
|
79
|
+
.optional()
|
|
80
|
+
.describe("Dashboard filter choices, one option per filter. Omit for the unfiltered dashboard. Salesforce keeps a separate cache for each filter option."),
|
|
81
|
+
maxRows: z
|
|
82
|
+
.number()
|
|
83
|
+
.int()
|
|
84
|
+
.min(1)
|
|
85
|
+
.max(HARD_ROW_CEILING)
|
|
86
|
+
.optional()
|
|
87
|
+
.describe(`Cap on detail rows per component. Default ${COMPONENT_ROWS}. Most components are charts over summary reports and return groups, not detail rows.`),
|
|
88
|
+
};
|
|
20
89
|
const resultControls = {
|
|
21
90
|
detail: z
|
|
22
91
|
.boolean()
|
|
@@ -32,7 +101,7 @@ const resultControls = {
|
|
|
32
101
|
};
|
|
33
102
|
export function buildServer(reports, options) {
|
|
34
103
|
const server = new McpServer({ name: "salesforce-reports", version: options.version ?? "0.1.0" }, {
|
|
35
|
-
instructions: "Find, define, run, save and combine Salesforce reports. To answer a data question without saving anything, use query_report. To re-run an existing report, use search_reports then run_report. Save a report (create_report, optionally with fromReportId to start from a saved one) only when the user asks for one.",
|
|
104
|
+
instructions: "Find, define, run, save and combine Salesforce reports, and read dashboards. To answer a data question without saving anything, use query_report. To re-run an existing report, use search_reports then run_report. For a dashboard, use list_dashboards then run_dashboard, and refresh_dashboard only when its data is missing or old. Save a report (create_report, optionally with fromReportId to start from a saved one) only when the user asks for one.",
|
|
36
105
|
});
|
|
37
106
|
async function baseUrl() {
|
|
38
107
|
try {
|
|
@@ -303,7 +372,92 @@ export function buildServer(reports, options) {
|
|
|
303
372
|
return fail(error);
|
|
304
373
|
}
|
|
305
374
|
});
|
|
375
|
+
// ---- dashboards: read tools ----
|
|
376
|
+
server.registerTool("list_dashboards", {
|
|
377
|
+
title: "List dashboards",
|
|
378
|
+
description: "Find Salesforce dashboards by title or developer name, optionally within a folder. Returns up to `limit` matches (default 25), most recently modified first, each with its id, title, developer name, folder, when its data was last refreshed (null if never) and a Lightning URL; a note says when more match. Use it first when the user names a dashboard. Next, describe_dashboard to see what it shows, or run_dashboard for its numbers. For saved reports, use search_reports.",
|
|
379
|
+
inputSchema: {
|
|
380
|
+
query: z.string().optional().describe("Text to find in the dashboard title or developer name. Omit to list the most recently modified dashboards."),
|
|
381
|
+
folder: z.string().optional().describe('Part of a folder name, for example "Sales".'),
|
|
382
|
+
limit: z.number().int().min(1).max(50).optional().describe("Maximum matches. Default 25."),
|
|
383
|
+
},
|
|
384
|
+
annotations: READ,
|
|
385
|
+
}, async ({ query, folder, limit }) => {
|
|
386
|
+
try {
|
|
387
|
+
const cap = limit ?? 25;
|
|
388
|
+
const rows = await reports.soql(dashboardListSoql({ query, folder, limit: cap }));
|
|
389
|
+
const kept = rows.slice(0, cap);
|
|
390
|
+
const base = await baseUrl();
|
|
391
|
+
// The SOQL field DashboardResultRefreshedDate stays null after a REST refresh, so the date comes from /status.
|
|
392
|
+
const refreshed = [];
|
|
393
|
+
for (let i = 0; i < kept.length; i += 5) {
|
|
394
|
+
refreshed.push(...(await Promise.all(kept.slice(i, i + 5).map(async (r) => {
|
|
395
|
+
try {
|
|
396
|
+
return latestRefresh(await reports.dashboardStatus(r.Id));
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
}))));
|
|
402
|
+
}
|
|
403
|
+
const notes = [];
|
|
404
|
+
if (rows.length > cap)
|
|
405
|
+
notes.push(`Showing the first ${cap} matches; more dashboards match. Narrow query or folder, or raise limit (up to 50).`);
|
|
406
|
+
if (refreshed.some((d) => d === null))
|
|
407
|
+
notes.push("lastRefreshed is null for a dashboard with no data yet: run_dashboard will say so, and refresh_dashboard fills it.");
|
|
408
|
+
return ok({
|
|
409
|
+
count: kept.length,
|
|
410
|
+
dashboards: kept.map((r, i) => ({
|
|
411
|
+
id: r.Id,
|
|
412
|
+
title: r.Title,
|
|
413
|
+
developerName: r.DeveloperName,
|
|
414
|
+
folder: r.FolderName,
|
|
415
|
+
folderId: r.FolderId,
|
|
416
|
+
description: r.Description,
|
|
417
|
+
runsAs: r.Type,
|
|
418
|
+
lastRefreshed: refreshed[i] ?? null,
|
|
419
|
+
lastModifiedDate: r.LastModifiedDate,
|
|
420
|
+
url: dashboardUrl(base, r.Id),
|
|
421
|
+
})),
|
|
422
|
+
notes,
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
return fail(error);
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
server.registerTool("describe_dashboard", {
|
|
430
|
+
title: "Describe a dashboard",
|
|
431
|
+
description: "Show what a dashboard contains without reading its data: its components in layout order (top to bottom, then left to right), each with its visualization type, header, title, source report id and name, grouping and measure, plus the dashboard's filters with their option labels and whose data it shows (the running user). Use it before run_dashboard to learn the filter names and options, or to find the saved report behind a chart and run it with run_report. Different from describe_report, which describes one saved report.",
|
|
432
|
+
inputSchema: { dashboardId },
|
|
433
|
+
annotations: READ,
|
|
434
|
+
}, async ({ dashboardId: id }) => {
|
|
435
|
+
try {
|
|
436
|
+
const describe = await reports.describeDashboard(id);
|
|
437
|
+
return ok(summarizeDashboard(describe, { baseUrl: await baseUrl(), reportNames: await reportNames(describe) }));
|
|
438
|
+
}
|
|
439
|
+
catch (error) {
|
|
440
|
+
return fail(error);
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
// run_dashboard and refresh_dashboard carry the dashboard card: every component drawn as its chart.
|
|
444
|
+
const DASHBOARD_VIEW = { ui: { resourceUri: DASHBOARD_VIEW_URI } };
|
|
445
|
+
registerAppTool(server, "run_dashboard", {
|
|
446
|
+
title: "Read a dashboard",
|
|
447
|
+
description: "Read a dashboard's numbers as Salesforce last refreshed them: per component its header, visualization type, status (data, no data, error) and a compact report result (groups and totals, the same shape run_report returns), plus the filters in words, whose data it shows and when it was refreshed. It never refreshes: a component with no data says so in notes, and notes give the data's age when it is older than a day; then offer refresh_dashboard. `filters` pick a dashboard filter option by name and label (see describe_dashboard). Use it when the user asks about a dashboard, or wants the set of figures a dashboard already gathers. Different from run_report, which runs one saved report live and can change its filters, groupings and dates for the run." + DASHBOARD_VIEW_HINT,
|
|
448
|
+
inputSchema: dashboardInputs,
|
|
449
|
+
annotations: READ,
|
|
450
|
+
_meta: DASHBOARD_VIEW,
|
|
451
|
+
}, async (args) => {
|
|
452
|
+
try {
|
|
453
|
+
return okView(await readDashboard(args));
|
|
454
|
+
}
|
|
455
|
+
catch (error) {
|
|
456
|
+
return fail(error);
|
|
457
|
+
}
|
|
458
|
+
});
|
|
306
459
|
registerAppResource(server, "Report view", REPORT_VIEW_URI, { description: "Draws a run_report or query_report result as a report card: title, filters, group table, totals, detail rows and notes." }, async () => ({ contents: [{ uri: REPORT_VIEW_URI, mimeType: RESOURCE_MIME_TYPE, text: reportViewHtml() }] }));
|
|
460
|
+
registerAppResource(server, "Dashboard view", DASHBOARD_VIEW_URI, { description: "Draws a run_dashboard or refresh_dashboard result as a dashboard card: header, filters, refresh time, and every component as its chart in layout order." }, async () => ({ contents: [{ uri: DASHBOARD_VIEW_URI, mimeType: RESOURCE_MIME_TYPE, text: dashboardViewHtml() }] }));
|
|
307
461
|
if (options.readOnly)
|
|
308
462
|
return server;
|
|
309
463
|
// ---- write tools ----
|
|
@@ -418,6 +572,20 @@ export function buildServer(reports, options) {
|
|
|
418
572
|
return fail(error);
|
|
419
573
|
}
|
|
420
574
|
});
|
|
575
|
+
registerAppTool(server, "refresh_dashboard", {
|
|
576
|
+
title: "Refresh a dashboard",
|
|
577
|
+
description: "Refresh a dashboard in Salesforce, so every component reruns its source report now, then return the same result as run_dashboard. It waits up to 60 seconds for the refresh to finish. Salesforce refreshes a dashboard at most once a minute: a second refresh inside a minute returns the cached results with a note saying when to try again. Each filter option has its own cache, so pass the filters you want to read. Use it when run_dashboard says a component has no data or the data is old, or when the user asks for current numbers. It saves nothing, but it runs every source report and changes what other viewers see, so it counts as a write. For one figure, run_report on the source report is lighter." + DASHBOARD_VIEW_HINT,
|
|
578
|
+
inputSchema: dashboardInputs,
|
|
579
|
+
annotations: WRITE,
|
|
580
|
+
_meta: DASHBOARD_VIEW,
|
|
581
|
+
}, async (args) => {
|
|
582
|
+
try {
|
|
583
|
+
return okView(await readDashboard(args, { refresh: true }));
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
return fail(error);
|
|
587
|
+
}
|
|
588
|
+
});
|
|
421
589
|
if (options.allowDelete) {
|
|
422
590
|
server.registerTool("delete_report", {
|
|
423
591
|
title: "Delete a report",
|
|
@@ -434,6 +602,45 @@ export function buildServer(reports, options) {
|
|
|
434
602
|
}
|
|
435
603
|
});
|
|
436
604
|
}
|
|
605
|
+
/**
|
|
606
|
+
* run_dashboard, and refresh_dashboard with `refresh`. Filters given by name and label are checked against
|
|
607
|
+
* describe before any data call, so a bad label costs no refresh.
|
|
608
|
+
*/
|
|
609
|
+
async function readDashboard(input, mode = {}) {
|
|
610
|
+
const id = input.dashboardId;
|
|
611
|
+
const resolved = input.filters?.length ? resolveFilters(await reports.describeDashboard(id), input.filters) : undefined;
|
|
612
|
+
const notes = mode.refresh ? await refreshAndWait(reports, id, resolved?.query ?? "", () => new Date()) : [];
|
|
613
|
+
const results = await reports.dashboardResults(id, resolved?.query ?? "");
|
|
614
|
+
const filters = resolved ?? resolveFilters(results.dashboardMetadata ?? {}, undefined);
|
|
615
|
+
const base = await baseUrl();
|
|
616
|
+
const shaped = shapeDashboard(results, {
|
|
617
|
+
baseUrl: base,
|
|
618
|
+
maxRows: Math.min(input.maxRows ?? COMPONENT_ROWS, HARD_ROW_CEILING),
|
|
619
|
+
filterWords: filters.words,
|
|
620
|
+
appliedFilters: filters.applied,
|
|
621
|
+
now: new Date(),
|
|
622
|
+
});
|
|
623
|
+
shaped.notes.unshift(...notes);
|
|
624
|
+
return dashboardView(results, shaped, base);
|
|
625
|
+
}
|
|
626
|
+
/** The names of a dashboard's source reports, by id. Empty when the lookup fails. */
|
|
627
|
+
async function reportNames(describe) {
|
|
628
|
+
const ids = [...new Set((describe.components ?? []).map((c) => c.reportId).filter((x) => Boolean(x)))];
|
|
629
|
+
const names = new Map();
|
|
630
|
+
if (!ids.length)
|
|
631
|
+
return names;
|
|
632
|
+
try {
|
|
633
|
+
const rows = await reports.soql(`SELECT Id, Name FROM Report WHERE Id IN (${ids.map((x) => `'${soqlString(x)}'`).join(", ")})`);
|
|
634
|
+
for (const r of rows) {
|
|
635
|
+
names.set(r.Id, r.Name);
|
|
636
|
+
names.set(String(r.Id).slice(0, 15), r.Name);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
catch {
|
|
640
|
+
/* names stay null: the ids still work with run_report */
|
|
641
|
+
}
|
|
642
|
+
return names;
|
|
643
|
+
}
|
|
437
644
|
async function orgPublicFolder() {
|
|
438
645
|
try {
|
|
439
646
|
const org = await reports.soql("SELECT Id FROM Organization");
|