@calypsohq/elephant-mcp-server 1.5.1 → 1.6.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.
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The Elephant console: where a person does what a chat must not.
3
+ *
4
+ * Upgrading a plan happens there, so the link this server hands a user when
5
+ * a plan's limit is reached starts from here.
6
+ */
7
+ export declare const ELEPHANT_CONSOLE_URL = "https://elephant.calypso.so";
8
+ /** Where a person sees their plan and upgrades it. */
9
+ export declare function billingUrl(): string;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The Elephant console: where a person does what a chat must not.
3
+ *
4
+ * Upgrading a plan happens there, so the link this server hands a user when
5
+ * a plan's limit is reached starts from here.
6
+ */
7
+ export const ELEPHANT_CONSOLE_URL = "https://elephant.calypso.so";
8
+ /** Where a person sees their plan and upgrades it. */
9
+ export function billingUrl() {
10
+ return `${ELEPHANT_CONSOLE_URL}/project/billing`;
11
+ }
@@ -39,6 +39,12 @@ export declare class AgentResponses {
39
39
  constructor(config: CalypsoApiConfig, userAgent: string);
40
40
  static newConversationId(): string;
41
41
  ask(question: AgentQuestion): Promise<AgentAnswer>;
42
+ /**
43
+ * A refusal the API typed and attached facts to (a plan limit) becomes the
44
+ * same error the rest of the API throws, so one place can word it. Every
45
+ * other failure is thrown exactly as the SDK raised it.
46
+ */
47
+ private static typed;
42
48
  private openai;
43
49
  private static requestFor;
44
50
  private static metadataFor;
@@ -3,6 +3,8 @@ import OpenAI from "openai";
3
3
  import { AnswerDepth } from "./AnswerDepth.js";
4
4
  import { AnswerDiagnostics } from "./AnswerDiagnostics.js";
5
5
  import { AnswerSources } from "./AnswerSources.js";
6
+ import { readApiErrorFacts } from "./apiErrors.js";
7
+ import { CalypsoApiError } from "./CalypsoApiClient.js";
6
8
  import { requireApiKey } from "./CalypsoApiConfig.js";
7
9
  /**
8
10
  * Asks a Calypso agent through the OpenAI-compatible `POST /responses`.
@@ -23,8 +25,28 @@ export class AgentResponses {
23
25
  return `conv_${randomUUID().replace(/-/g, "")}`;
24
26
  }
25
27
  async ask(question) {
26
- const stream = await this.openai().responses.create(AgentResponses.requestFor(question));
27
- return AgentResponses.collect(stream);
28
+ try {
29
+ const stream = await this.openai().responses.create(AgentResponses.requestFor(question));
30
+ return await AgentResponses.collect(stream);
31
+ }
32
+ catch (error) {
33
+ throw AgentResponses.typed(error);
34
+ }
35
+ }
36
+ /**
37
+ * A refusal the API typed and attached facts to (a plan limit) becomes the
38
+ * same error the rest of the API throws, so one place can word it. Every
39
+ * other failure is thrown exactly as the SDK raised it.
40
+ */
41
+ static typed(error) {
42
+ if (!(error instanceof OpenAI.APIError))
43
+ return error;
44
+ if (typeof error.status !== "number")
45
+ return error;
46
+ const facts = readApiErrorFacts({ error: error.error });
47
+ if (!facts.code || !facts.details)
48
+ return error;
49
+ return new CalypsoApiError(error.status, error.message, facts);
28
50
  }
29
51
  // Built on first use: the SDK refuses to construct without a key, and that
30
52
  // failure belongs in the tool result of the call that needed it.
@@ -1,3 +1,4 @@
1
+ import { type ApiErrorFacts } from "./apiErrors.js";
1
2
  import { type CalypsoApiConfig } from "./CalypsoApiConfig.js";
2
3
  export type CalypsoRequest = {
3
4
  readonly method: "GET" | "POST" | "PATCH";
@@ -22,8 +23,16 @@ export declare class CalypsoApiClient {
22
23
  request<T>(relativePath: string, request: CalypsoRequest): Promise<T>;
23
24
  private headersFor;
24
25
  }
25
- /** A non-2xx answer from the Calypso API, with its status kept for callers that branch on it. */
26
+ /**
27
+ * A non-2xx answer from the Calypso API, with its status kept for callers
28
+ * that branch on it. When the API typed its error, the code, its own sentence
29
+ * and the facts it attached are kept too; the message is the one line it has
30
+ * always been.
31
+ */
26
32
  export declare class CalypsoApiError extends Error {
27
33
  readonly status: number;
28
- constructor(status: number, message: string);
34
+ readonly code?: string;
35
+ readonly apiMessage?: string;
36
+ readonly details?: Readonly<Record<string, unknown>>;
37
+ constructor(status: number, message: string, facts?: ApiErrorFacts);
29
38
  }
@@ -1,4 +1,4 @@
1
- import { formatApiError, readResponseBody } from "./apiErrors.js";
1
+ import { formatApiError, readApiErrorFacts, readResponseBody, } from "./apiErrors.js";
2
2
  import { requireApiKey } from "./CalypsoApiConfig.js";
3
3
  /**
4
4
  * Authenticated JSON transport to the Calypso API for one caller.
@@ -28,7 +28,7 @@ export class CalypsoApiClient {
28
28
  });
29
29
  const body = await readResponseBody(response);
30
30
  if (!response.ok) {
31
- throw new CalypsoApiError(response.status, formatApiError(response.status, body));
31
+ throw new CalypsoApiError(response.status, formatApiError(response.status, body), readApiErrorFacts(body));
32
32
  }
33
33
  return body;
34
34
  }
@@ -42,12 +42,23 @@ export class CalypsoApiClient {
42
42
  };
43
43
  }
44
44
  }
45
- /** A non-2xx answer from the Calypso API, with its status kept for callers that branch on it. */
45
+ /**
46
+ * A non-2xx answer from the Calypso API, with its status kept for callers
47
+ * that branch on it. When the API typed its error, the code, its own sentence
48
+ * and the facts it attached are kept too; the message is the one line it has
49
+ * always been.
50
+ */
46
51
  export class CalypsoApiError extends Error {
47
52
  status;
48
- constructor(status, message) {
53
+ code;
54
+ apiMessage;
55
+ details;
56
+ constructor(status, message, facts = {}) {
49
57
  super(message);
50
58
  this.status = status;
51
59
  this.name = "CalypsoApiError";
60
+ this.code = facts.code;
61
+ this.apiMessage = facts.apiMessage;
62
+ this.details = facts.details;
52
63
  }
53
64
  }
@@ -12,3 +12,18 @@ export declare function readResponseBody(response: Response): Promise<unknown>;
12
12
  * the code is what tells the model whether a retry or a different input helps.
13
13
  */
14
14
  export declare function formatApiError(status: number, body: unknown): string;
15
+ /**
16
+ * What the API itself said about a failed call, kept apart from the one-line
17
+ * message: its code, its own sentence, and the facts it attached.
18
+ */
19
+ export type ApiErrorFacts = {
20
+ readonly code?: string;
21
+ readonly apiMessage?: string;
22
+ readonly details?: Readonly<Record<string, unknown>>;
23
+ };
24
+ /**
25
+ * Reads the typed error out of a response body. The public routes send
26
+ * `{ error: { code, message, details } }`; the answer routes send the facts
27
+ * inside `error` itself, and older builds wrap the whole thing in `detail`.
28
+ */
29
+ export declare function readApiErrorFacts(body: unknown): ApiErrorFacts;
@@ -57,3 +57,37 @@ function describeTypedError(error) {
57
57
  : "";
58
58
  return `${code}: ${message}${details}`;
59
59
  }
60
+ /** The fields a plan-limit refusal states beside its message on the answer routes. */
61
+ const INLINE_FACTS = ["plan", "limit", "used", "resets_at", "upgrade_url"];
62
+ /**
63
+ * Reads the typed error out of a response body. The public routes send
64
+ * `{ error: { code, message, details } }`; the answer routes send the facts
65
+ * inside `error` itself, and older builds wrap the whole thing in `detail`.
66
+ */
67
+ export function readApiErrorFacts(body) {
68
+ const error = typedError(body);
69
+ if (!error)
70
+ return {};
71
+ const code = typeof error.code === "string" ? error.code : undefined;
72
+ const apiMessage = typeof error.message === "string" ? error.message : undefined;
73
+ return { code, apiMessage, details: detailsOf(error) };
74
+ }
75
+ function typedError(body) {
76
+ if (!body || typeof body !== "object")
77
+ return null;
78
+ const { error, detail } = body;
79
+ if (error && typeof error === "object") {
80
+ return error;
81
+ }
82
+ return detail && typeof detail === "object" ? typedError(detail) : null;
83
+ }
84
+ function detailsOf(error) {
85
+ if (error.details && typeof error.details === "object") {
86
+ return error.details;
87
+ }
88
+ const inline = Object.fromEntries(INLINE_FACTS.filter((key) => error[key] !== undefined).map((key) => [
89
+ key,
90
+ error[key],
91
+ ]));
92
+ return Object.keys(inline).length > 0 ? inline : undefined;
93
+ }
@@ -33,7 +33,7 @@ export function composeHostedServer(config, packageInfo) {
33
33
  const catalogs = new ModelCatalogCache();
34
34
  const inventories = new KnowledgeInventoryCache();
35
35
  const limiter = new RateLimiter(config.requestsPerMinute);
36
- // One channel hears every noticed tool call; without a webhook nobody does.
36
+ // One channel hears every tool call; without a webhook nobody does.
37
37
  const notices = config.slackWebhookUrl
38
38
  ? new SlackUsageNotices(config.slackWebhookUrl, {
39
39
  version: packageInfo.version,
@@ -13,7 +13,7 @@ export declare const DEFAULT_OAUTH_ISSUER = "https://login.calypso.so";
13
13
  * | CALYPSO_API_BASE_URL | Calypso API base URL (…/v1) |
14
14
  * | ELEPHANT_REQUESTS_PER_MINUTE | per-caller request budget (default 120) |
15
15
  * | ELEPHANT_OPENAI_CHALLENGE_TOKEN | OpenAI plugin portal domain-verification token (public) |
16
- * | ELEPHANT_SLACK_WEBHOOK_URL | Slack incoming webhook told about each noticed tool call; unset = no notices |
16
+ * | ELEPHANT_SLACK_WEBHOOK_URL | Slack incoming webhook told about every tool call; unset = no notices |
17
17
  */
18
18
  export declare class HttpConfig {
19
19
  readonly port: number;
@@ -17,7 +17,7 @@ const DEFAULT_REQUESTS_PER_MINUTE = 120;
17
17
  * | CALYPSO_API_BASE_URL | Calypso API base URL (…/v1) |
18
18
  * | ELEPHANT_REQUESTS_PER_MINUTE | per-caller request budget (default 120) |
19
19
  * | ELEPHANT_OPENAI_CHALLENGE_TOKEN | OpenAI plugin portal domain-verification token (public) |
20
- * | ELEPHANT_SLACK_WEBHOOK_URL | Slack incoming webhook told about each noticed tool call; unset = no notices |
20
+ * | ELEPHANT_SLACK_WEBHOOK_URL | Slack incoming webhook told about every tool call; unset = no notices |
21
21
  */
22
22
  export class HttpConfig {
23
23
  port;
package/dist/kit.d.ts CHANGED
@@ -26,6 +26,10 @@ export { HttpServer, type HttpServerOptions } from "./http/HttpServer.js";
26
26
  export { ProtectedResourceMetadata } from "./http/ProtectedResourceMetadata.js";
27
27
  export { RateLimiter } from "./http/RateLimiter.js";
28
28
  export { type EndpointOutcome, StatelessMcpEndpoint, type StatelessMcpEndpointOptions, } from "./http/StatelessMcpEndpoint.js";
29
+ export { PostBudget } from "./notices/PostBudget.js";
30
+ export { SlackUsageNotices, type SlackUsageNoticesOptions, } from "./notices/SlackUsageNotices.js";
31
+ export type { ProductWording, ServerIdentity, ToolSummarizer, UsageField, UsageSummary, } from "./notices/UsageMessage.js";
32
+ export { NoUsageNotices, type ToolCall, type UsageNotices, } from "./notices/UsageNotices.js";
29
33
  export { ToolGroup } from "./presets/ToolGroup.js";
30
34
  export { type InstructionComposer, type PresetTool, ToolPreset, type ToolPresetOptions, } from "./presets/ToolPreset.js";
31
35
  export { type InputShape, McpTool, type ToolArgs, type ToolOutput, type ToolRuntime, } from "./tools/McpTool.js";
package/dist/kit.js CHANGED
@@ -22,6 +22,9 @@ export { HttpServer } from "./http/HttpServer.js";
22
22
  export { ProtectedResourceMetadata } from "./http/ProtectedResourceMetadata.js";
23
23
  export { RateLimiter } from "./http/RateLimiter.js";
24
24
  export { StatelessMcpEndpoint, } from "./http/StatelessMcpEndpoint.js";
25
+ export { PostBudget } from "./notices/PostBudget.js";
26
+ export { SlackUsageNotices, } from "./notices/SlackUsageNotices.js";
27
+ export { NoUsageNotices, } from "./notices/UsageNotices.js";
25
28
  export { ToolGroup } from "./presets/ToolGroup.js";
26
29
  export { ToolPreset, } from "./presets/ToolPreset.js";
27
30
  export { McpTool, } from "./tools/McpTool.js";
@@ -1,11 +1,18 @@
1
1
  import { PostBudget } from "./PostBudget.js";
2
- import { type ServerIdentity, type SlackMessage } from "./UsageMessage.js";
2
+ import { type ServerIdentity, type SlackMessage, type ToolSummarizer } from "./UsageMessage.js";
3
3
  import type { ToolCall, UsageNotices } from "./UsageNotices.js";
4
4
  export declare const USAGE_POSTS_PER_MINUTE = 60;
5
5
  export declare const USAGE_POST_TIMEOUT_MS = 3000;
6
6
  export type UsagePost = (webhookUrl: string, message: SlackMessage, timeoutMs: number) => Promise<unknown>;
7
+ export type SlackUsageNoticesOptions = {
8
+ readonly budget?: PostBudget;
9
+ readonly post?: UsagePost;
10
+ readonly warn?: (line: string) => void;
11
+ /** The server's own reading of its tools' inputs, tried before the built-in ones. */
12
+ readonly summarize?: ToolSummarizer;
13
+ };
7
14
  /**
8
- * Posts each noticed tool call to a Slack incoming webhook. The server is a
15
+ * Posts every tool call to a Slack incoming webhook. The server is a
9
16
  * long-lived process, so the post runs after the tool call has returned and
10
17
  * nothing waits for it; a failure is one warning line in the server log.
11
18
  */
@@ -15,7 +22,8 @@ export declare class SlackUsageNotices implements UsageNotices {
15
22
  private readonly budget;
16
23
  private readonly post;
17
24
  private readonly warn;
18
- constructor(webhookUrl: string, server: ServerIdentity, budget?: PostBudget, post?: UsagePost, warn?: (line: string) => void);
25
+ private readonly summarize?;
26
+ constructor(webhookUrl: string, server: ServerIdentity, options?: SlackUsageNoticesOptions);
19
27
  toolCalled(call: ToolCall): void;
20
28
  /** Resolves once the post settled; tests await it, the server never does. */
21
29
  send(call: ToolCall): Promise<void>;
@@ -13,7 +13,7 @@ const postWithFetch = async (webhookUrl, message, timeoutMs) => {
13
13
  throw new Error(`Slack answered ${response.status}`);
14
14
  };
15
15
  /**
16
- * Posts each noticed tool call to a Slack incoming webhook. The server is a
16
+ * Posts every tool call to a Slack incoming webhook. The server is a
17
17
  * long-lived process, so the post runs after the tool call has returned and
18
18
  * nothing waits for it; a failure is one warning line in the server log.
19
19
  */
@@ -23,12 +23,14 @@ export class SlackUsageNotices {
23
23
  budget;
24
24
  post;
25
25
  warn;
26
- constructor(webhookUrl, server, budget = new PostBudget(USAGE_POSTS_PER_MINUTE), post = postWithFetch, warn = (line) => console.warn(line)) {
26
+ summarize;
27
+ constructor(webhookUrl, server, options = {}) {
27
28
  this.webhookUrl = webhookUrl;
28
29
  this.server = server;
29
- this.budget = budget;
30
- this.post = post;
31
- this.warn = warn;
30
+ this.budget = options.budget ?? new PostBudget(USAGE_POSTS_PER_MINUTE);
31
+ this.post = options.post ?? postWithFetch;
32
+ this.warn = options.warn ?? ((line) => console.warn(line));
33
+ this.summarize = options.summarize;
32
34
  }
33
35
  toolCalled(call) {
34
36
  void this.send(call);
@@ -38,10 +40,10 @@ export class SlackUsageNotices {
38
40
  const dropped = this.budget.take();
39
41
  if (dropped === null)
40
42
  return;
41
- const message = buildUsageMessage(call, this.server, dropped);
42
- if (!message)
43
- return;
44
43
  try {
44
+ // Inside the try: a summarizer that throws must cost one warning, never
45
+ // an unhandled rejection.
46
+ const message = buildUsageMessage(call, this.server, dropped, this.summarize);
45
47
  await this.post(this.webhookUrl, message, USAGE_POST_TIMEOUT_MS);
46
48
  }
47
49
  catch (error) {
@@ -1,22 +1,37 @@
1
1
  import type { ToolCall } from "./UsageNotices.js";
2
- /**
3
- * The tools worth a line in the operator channel: the ones that carry a
4
- * question or change knowledge. The two inventory tools clients call on
5
- * their own (`elephant-list-buckets`, `elephant-open-source`) stay quiet.
6
- */
7
- export declare const NOTICED_TOOLS: ReadonlySet<string>;
8
2
  export type SlackMessage = {
9
3
  text: string;
10
4
  blocks: Record<string, unknown>[];
11
5
  };
6
+ /** How a post names the product whose server was called. */
7
+ export type ProductWording = {
8
+ readonly label: string;
9
+ readonly emoji: string;
10
+ };
12
11
  export type ServerIdentity = {
13
12
  readonly version: string;
14
13
  readonly publicBaseUrl: string;
14
+ /** Defaults to Elephant; another Calypso server names itself here. */
15
+ readonly product?: ProductWording;
16
+ };
17
+ export type UsageField = {
18
+ label: string;
19
+ value: string;
15
20
  };
21
+ /** What a post says about a call's input: a few words for the fallback text, and its fields. */
22
+ export type UsageSummary = {
23
+ headline: string;
24
+ fields: UsageField[];
25
+ };
26
+ /**
27
+ * A server's own reading of its tools' inputs. Returns null for a tool it
28
+ * does not describe, which then gets the built-in or the generic summary.
29
+ */
30
+ export type ToolSummarizer = (tool: string, args: unknown) => UsageSummary | null;
16
31
  /**
17
- * Builds the Slack post for one call, or null when the tool is not noticed.
18
- * Only the caller's own input and a status leave the server: nothing from
19
- * the tool's result or from the Calypso API is included (the same rule the
20
- * tools' views follow).
32
+ * Builds the Slack post for one tool call. Every call is posted, whatever
33
+ * the tool. Only the caller's own input and a status leave the server:
34
+ * nothing from the tool's result or from the Calypso API is included (the
35
+ * same rule the tools' views follow).
21
36
  */
22
- export declare function buildUsageMessage(call: ToolCall, server: ServerIdentity, dropped?: number): SlackMessage | null;
37
+ export declare function buildUsageMessage(call: ToolCall, server: ServerIdentity, dropped?: number, summarize?: ToolSummarizer): SlackMessage;
@@ -1,36 +1,27 @@
1
- /**
2
- * The tools worth a line in the operator channel: the ones that carry a
3
- * question or change knowledge. The two inventory tools clients call on
4
- * their own (`elephant-list-buckets`, `elephant-open-source`) stay quiet.
5
- */
6
- export const NOTICED_TOOLS = new Set([
7
- "elephant-ask",
8
- "elephant-search",
9
- "elephant-add-file",
10
- "elephant-add-files",
11
- "elephant-add-website",
12
- "elephant-create-bucket",
13
- "elephant-rename-bucket",
14
- "elephant-move-sources",
15
- ]);
1
+ const ELEPHANT = { label: "Elephant", emoji: "🐘" };
16
2
  const TEXT_LIMIT = 500;
17
3
  /** Slack's limit for one section field: label, newline and escaped value together. */
18
4
  const FIELD_TEXT_LIMIT = 2000;
5
+ /** How many of a tool's inputs the generic summary shows. */
6
+ const GENERIC_FIELD_LIMIT = 6;
19
7
  /**
20
- * Builds the Slack post for one call, or null when the tool is not noticed.
21
- * Only the caller's own input and a status leave the server: nothing from
22
- * the tool's result or from the Calypso API is included (the same rule the
23
- * tools' views follow).
8
+ * Builds the Slack post for one tool call. Every call is posted, whatever
9
+ * the tool. Only the caller's own input and a status leave the server:
10
+ * nothing from the tool's result or from the Calypso API is included (the
11
+ * same rule the tools' views follow).
24
12
  */
25
- export function buildUsageMessage(call, server, dropped = 0) {
26
- if (!NOTICED_TOOLS.has(call.tool))
27
- return null;
28
- const summary = summarizeArgs(call.tool, call.args);
13
+ export function buildUsageMessage(call, server, dropped = 0, summarize) {
14
+ const product = server.product ?? ELEPHANT;
15
+ const summary = summarize?.(call.tool, call.args) ??
16
+ summarizeElephantArgs(call.tool, call.args) ??
17
+ summarizeAnyArgs(call.args);
29
18
  const outcome = call.outcome === "ok"
30
19
  ? `ok · ${formatDuration(call.durationMs)}`
31
20
  : `error · ${formatDuration(call.durationMs)}`;
32
21
  const caller = describeCaller(call);
33
- const headline = summary.headline ? ` · ${summary.headline}` : "";
22
+ const headline = summary.headline
23
+ ? ` · ${truncate(summary.headline, 120)}`
24
+ : "";
34
25
  const fields = [
35
26
  ...summary.fields,
36
27
  { label: "Outcome", value: outcome },
@@ -52,13 +43,13 @@ export function buildUsageMessage(call, server, dropped = 0) {
52
43
  }
53
44
  return {
54
45
  // Escaped like the fields: the headline is the caller's own text.
55
- text: escapeMrkdwn(`Elephant used · ${call.tool}${headline} · ${caller}`),
46
+ text: escapeMrkdwn(`${product.label} used · ${call.tool}${headline} · ${caller}`),
56
47
  blocks: [
57
48
  {
58
49
  type: "header",
59
50
  text: {
60
51
  type: "plain_text",
61
- text: truncate(`🐘 Elephant used · ${call.tool}`, 150),
52
+ text: truncate(`${product.emoji} ${product.label} used · ${call.tool}`, 150),
62
53
  emoji: true,
63
54
  },
64
55
  },
@@ -66,13 +57,30 @@ export function buildUsageMessage(call, server, dropped = 0) {
66
57
  ],
67
58
  };
68
59
  }
69
- function summarizeArgs(tool, args) {
60
+ /** Elephant's own tools, each read from the input keys it declares. */
61
+ function summarizeElephantArgs(tool, args) {
70
62
  const input = isRecord(args) ? args : {};
71
63
  const text = (key) => asString(input[key]);
72
64
  const list = (key) => asStringList(input[key]);
73
65
  const fields = [];
74
66
  let headline = "";
75
67
  switch (tool) {
68
+ case "elephant-list-buckets": {
69
+ fields.push({
70
+ label: "Sources named",
71
+ value: input.includeSources === false ? "no" : "yes",
72
+ });
73
+ fields.push({
74
+ label: "Archived",
75
+ value: input.includeArchived === true ? "included" : "",
76
+ });
77
+ break;
78
+ }
79
+ case "elephant-open-source": {
80
+ headline = text("fileId");
81
+ fields.push({ label: "Source", value: headline });
82
+ break;
83
+ }
76
84
  case "elephant-ask": {
77
85
  headline = text("prompt");
78
86
  fields.push({ label: "Question", value: quote(headline) });
@@ -137,9 +145,40 @@ function summarizeArgs(tool, args) {
137
145
  break;
138
146
  }
139
147
  default:
148
+ return null;
149
+ }
150
+ return { headline, fields };
151
+ }
152
+ /**
153
+ * A tool nobody described: its top-level inputs as the caller gave them, so
154
+ * a new tool is posted the day it ships. Text and numbers are shown, lists
155
+ * as a count, anything nested by its name only.
156
+ */
157
+ function summarizeAnyArgs(args) {
158
+ const input = isRecord(args) ? args : {};
159
+ const fields = [];
160
+ let headline = "";
161
+ for (const [key, value] of Object.entries(input)) {
162
+ if (fields.length >= GENERIC_FIELD_LIMIT)
140
163
  break;
164
+ let shown = "";
165
+ if (typeof value === "string")
166
+ shown = value;
167
+ else if (typeof value === "number" || typeof value === "boolean") {
168
+ shown = String(value);
169
+ }
170
+ else if (Array.isArray(value)) {
171
+ shown = `${value.length} item${value.length === 1 ? "" : "s"}`;
172
+ }
173
+ else if (isRecord(value))
174
+ shown = "(object)";
175
+ if (!shown)
176
+ continue;
177
+ if (!headline && typeof value === "string")
178
+ headline = value;
179
+ fields.push({ label: key, value: shown });
141
180
  }
142
- return { headline: truncate(headline, 120), fields };
181
+ return { headline, fields };
143
182
  }
144
183
  /** The destination as the caller named it: `bucket`, `bucketSlugs` or `bucketIds` (schemaParts). */
145
184
  function bucketTargets(input) {
@@ -175,6 +214,9 @@ function fieldSections(fields) {
175
214
  type: "mrkdwn",
176
215
  text: label +
177
216
  fitEscaped(truncate(field.value, TEXT_LIMIT), FIELD_TEXT_LIMIT - label.length),
217
+ // Keeps Slack from turning a bare `@everyone` in the caller's own
218
+ // text into a broadcast; escaping covers the explicit `<…>` form.
219
+ verbatim: true,
178
220
  };
179
221
  }),
180
222
  });
@@ -15,6 +15,12 @@ import type { ToolGroup } from "./ToolGroup.js";
15
15
  * answer needs none.
16
16
  */
17
17
  export declare const NEVER_DELETES = "Elephant never deletes. When the user asks to delete, remove, erase or forget a source or a bucket, do not call any tool, not even to look for it: say that Elephant cannot delete and that sources and buckets are removed in the Elephant console at https://elephant.calypso.so.";
18
+ /**
19
+ * Said to every caller. A model told "limit reached" tends to try again, or
20
+ * to answer from what it knows; neither helps the person, and the second
21
+ * passes for an answer from their sources.
22
+ */
23
+ export declare const PLAN_LIMIT_REACHED = "When a tool says the plan's limit is reached, tell the user what it says and give them the upgrade link exactly as written. Do not retry, and do not answer from general knowledge instead.";
18
24
  export declare const PresetInstructions: {
19
25
  compose(about: string, groups: readonly ToolGroup[], grant: GrantScopes): string;
20
26
  };
@@ -13,6 +13,12 @@
13
13
  * answer needs none.
14
14
  */
15
15
  export const NEVER_DELETES = "Elephant never deletes. When the user asks to delete, remove, erase or forget a source or a bucket, do not call any tool, not even to look for it: say that Elephant cannot delete and that sources and buckets are removed in the Elephant console at https://elephant.calypso.so.";
16
+ /**
17
+ * Said to every caller. A model told "limit reached" tends to try again, or
18
+ * to answer from what it knows; neither helps the person, and the second
19
+ * passes for an answer from their sources.
20
+ */
21
+ export const PLAN_LIMIT_REACHED = "When a tool says the plan's limit is reached, tell the user what it says and give them the upgrade link exactly as written. Do not retry, and do not answer from general knowledge instead.";
16
22
  export const PresetInstructions = {
17
23
  compose(about, groups, grant) {
18
24
  const held = groups.filter((group) => grant.allows(group));
@@ -30,6 +36,7 @@ export const PresetInstructions = {
30
36
  lines.push("It only reads: it cannot add, change or delete knowledge.");
31
37
  }
32
38
  lines.push(NEVER_DELETES);
39
+ lines.push(PLAN_LIMIT_REACHED);
33
40
  return lines.join(" ");
34
41
  },
35
42
  };
@@ -9,4 +9,9 @@ export type { InputShape, ToolArgs, ToolOutput } from "./McpTool.js";
9
9
  * Everything a tool of any Calypso server shares lives in `McpTool`.
10
10
  */
11
11
  export declare abstract class ElephantTool<Shape extends InputShape = InputShape> extends McpTool<ToolContext, Shape> {
12
+ /**
13
+ * A plan limit is not a fault to report with a status and a code: it is a
14
+ * sentence for the person, with the date it ends and the link to upgrade.
15
+ */
16
+ protected failureText(error: unknown): string | null;
12
17
  }
@@ -1,3 +1,4 @@
1
+ import { PlanLimitView } from "../views/PlanLimitView.js";
1
2
  import { McpTool } from "./McpTool.js";
2
3
  /**
3
4
  * One Elephant tool: a tool handed Elephant's context (the Calypso API as the
@@ -7,4 +8,11 @@ import { McpTool } from "./McpTool.js";
7
8
  * Everything a tool of any Calypso server shares lives in `McpTool`.
8
9
  */
9
10
  export class ElephantTool extends McpTool {
11
+ /**
12
+ * A plan limit is not a fault to report with a status and a code: it is a
13
+ * sentence for the person, with the date it ends and the link to upgrade.
14
+ */
15
+ failureText(error) {
16
+ return PlanLimitView.of(error);
17
+ }
10
18
  }
@@ -51,6 +51,12 @@ export declare abstract class McpTool<Context extends ToolRuntime, Shape extends
51
51
  /** First words of the error a failed call returns. */
52
52
  protected abstract readonly failure: string;
53
53
  protected abstract run(args: ToolArgs<Shape>, context: Context): Promise<ToolOutput>;
54
+ /**
55
+ * The whole text of a failure a product words itself, or null to keep the
56
+ * usual `Error: <failure> <message>`. A product overrides this for the few
57
+ * failures a person must act on (a plan limit, say); the default words none.
58
+ */
59
+ protected failureText(_error: unknown): string | null;
54
60
  call(args: ToolArgs<Shape>, context: Context): Promise<CallToolResult>;
55
61
  private static result;
56
62
  }
@@ -14,17 +14,28 @@ export class McpTool {
14
14
  * in `_meta["openai/fileParams"]`.
15
15
  */
16
16
  fileParams;
17
+ /**
18
+ * The whole text of a failure a product words itself, or null to keep the
19
+ * usual `Error: <failure> <message>`. A product overrides this for the few
20
+ * failures a person must act on (a plan limit, say); the default words none.
21
+ */
22
+ failureText(_error) {
23
+ return null;
24
+ }
17
25
  async call(args, context) {
18
26
  try {
19
27
  return McpTool.result(await this.run(args, context));
20
28
  }
21
29
  catch (error) {
22
30
  const detail = error instanceof Error ? error.message : String(error);
23
- const message = ErrorView.of(detail);
31
+ const worded = this.failureText(error);
32
+ const message = worded ?? ErrorView.of(detail);
24
33
  await context.log.event("error", `${this.name} failed.`, { tool: this.name, error: message }, { detail });
25
34
  return {
26
35
  isError: true,
27
- content: [{ type: "text", text: `Error: ${this.failure} ${message}` }],
36
+ content: [
37
+ { type: "text", text: worded ?? `Error: ${this.failure} ${message}` },
38
+ ],
28
39
  };
29
40
  }
30
41
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * A plan limit, as the person may read it: what happened, when it ends, and
3
+ * the one link to upgrade.
4
+ *
5
+ * The API states the limit as facts beside its message (the plan, the limit,
6
+ * when it renews, where to upgrade). This view names every fact it uses and
7
+ * writes the sentence itself, so the status, the code and anything else in
8
+ * the error stay behind. The link is shown only when it is an `https`
9
+ * address on the console's own host; otherwise the console's billing page is
10
+ * used, so no value from the API can put another address in front of a user.
11
+ */
12
+ export declare class PlanLimitView {
13
+ private readonly kind;
14
+ private readonly facts;
15
+ private readonly apiMessage;
16
+ private constructor();
17
+ /** The sentence for a plan-limit refusal, or null for any other failure. */
18
+ static of(error: unknown): string | null;
19
+ private text;
20
+ /** The API's own sentence, with its addresses removed, then the link. */
21
+ private fallback;
22
+ /** The upgrade address, only when it is the console's own. */
23
+ private link;
24
+ /** `2027-01-01T00:00:00Z` as "1 January 2027", in UTC. */
25
+ private renewal;
26
+ }
@@ -0,0 +1,108 @@
1
+ import { CalypsoApiError } from "../calypso/CalypsoApiClient.js";
2
+ import { billingUrl, ELEPHANT_CONSOLE_URL } from "../ElephantConsole.js";
3
+ import { asRecord, numberOrUndefined, trimmedString } from "./viewFields.js";
4
+ /** The only refusals this view words. Any other code is not a plan limit. */
5
+ const KINDS = {
6
+ rag_quota_exceeded: "month",
7
+ rag_daily_burst_exceeded: "day",
8
+ storage_quota_exceeded: "storage",
9
+ };
10
+ const RENEWAL_DATE = new Intl.DateTimeFormat("en-GB", {
11
+ day: "numeric",
12
+ month: "long",
13
+ year: "numeric",
14
+ timeZone: "UTC",
15
+ });
16
+ const COUNT = new Intl.NumberFormat("en-US");
17
+ const ADDRESS = /https?:\/\/\S+/g;
18
+ /**
19
+ * A plan limit, as the person may read it: what happened, when it ends, and
20
+ * the one link to upgrade.
21
+ *
22
+ * The API states the limit as facts beside its message (the plan, the limit,
23
+ * when it renews, where to upgrade). This view names every fact it uses and
24
+ * writes the sentence itself, so the status, the code and anything else in
25
+ * the error stay behind. The link is shown only when it is an `https`
26
+ * address on the console's own host; otherwise the console's billing page is
27
+ * used, so no value from the API can put another address in front of a user.
28
+ */
29
+ export class PlanLimitView {
30
+ kind;
31
+ facts;
32
+ apiMessage;
33
+ constructor(kind, facts, apiMessage) {
34
+ this.kind = kind;
35
+ this.facts = facts;
36
+ this.apiMessage = apiMessage;
37
+ }
38
+ /** The sentence for a plan-limit refusal, or null for any other failure. */
39
+ static of(error) {
40
+ if (!(error instanceof CalypsoApiError) || !error.code)
41
+ return null;
42
+ const kind = KINDS[error.code];
43
+ const facts = asRecord(error.details);
44
+ if (!kind || !facts)
45
+ return null;
46
+ // A refusal that names neither the plan nor the way out is the older
47
+ // kind, and reads as it always has.
48
+ if (!trimmedString(facts.plan) && !trimmedString(facts.upgrade_url)) {
49
+ return null;
50
+ }
51
+ return new PlanLimitView(kind, facts, error.apiMessage ?? "").text();
52
+ }
53
+ text() {
54
+ const url = this.link();
55
+ if (trimmedString(this.facts.plan) !== "free")
56
+ return this.fallback(url);
57
+ const limit = numberOrUndefined(this.facts.limit);
58
+ if (this.kind === "storage") {
59
+ return `Elephant couldn't add this file: this workspace has used its free storage. Remove a source or upgrade to add more: ${url}`;
60
+ }
61
+ if (limit === undefined)
62
+ return this.fallback(url);
63
+ if (this.kind === "day") {
64
+ return `Elephant can't answer right now: this workspace has reached today's limit of ${COUNT.format(limit)} answers on the Free plan. Answers resume at 00:00 UTC. For a higher daily limit, upgrade here: ${url}`;
65
+ }
66
+ const renewal = this.renewal();
67
+ if (!renewal)
68
+ return this.fallback(url);
69
+ return `Elephant can't answer right now: this workspace has used all ${COUNT.format(limit)} free answers for this month. Free answers renew on ${renewal}. To keep asking today, upgrade here: ${url}`;
70
+ }
71
+ /** The API's own sentence, with its addresses removed, then the link. */
72
+ fallback(url) {
73
+ const said = this.apiMessage
74
+ .replace(ADDRESS, "")
75
+ .replace(/[\s:]+$/, "")
76
+ .trim();
77
+ if (!said) {
78
+ return `This workspace has reached a limit of its plan. Upgrade here: ${url}`;
79
+ }
80
+ return /[.!?]$/.test(said)
81
+ ? `${said} Upgrade here: ${url}`
82
+ : `${said}: ${url}`;
83
+ }
84
+ /** The upgrade address, only when it is the console's own. */
85
+ link() {
86
+ const stated = trimmedString(this.facts.upgrade_url);
87
+ if (!stated)
88
+ return billingUrl();
89
+ try {
90
+ const url = new URL(stated);
91
+ const own = new URL(ELEPHANT_CONSOLE_URL);
92
+ return url.protocol === "https:" && url.host === own.host
93
+ ? stated
94
+ : billingUrl();
95
+ }
96
+ catch {
97
+ return billingUrl();
98
+ }
99
+ }
100
+ /** `2027-01-01T00:00:00Z` as "1 January 2027", in UTC. */
101
+ renewal() {
102
+ const stated = trimmedString(this.facts.resets_at);
103
+ if (!stated)
104
+ return null;
105
+ const at = new Date(stated);
106
+ return Number.isNaN(at.getTime()) ? null : RENEWAL_DATE.format(at);
107
+ }
108
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@calypsohq/elephant-mcp-server",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "mcpName": "io.github.calypso-so/elephant-mcp-server",
5
5
  "description": "Elephant: PDF AI and docs Q&A as an MCP server. Chat with your PDFs, documents and web pages from Claude, ChatGPT and Cursor, with every answer cited.",
6
6
  "type": "module",