@calypsohq/elephant-mcp-server 1.3.3 → 1.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/README.md CHANGED
@@ -59,6 +59,7 @@ An unauthenticated request gets `401` with `WWW-Authenticate: Bearer resource_me
59
59
  | `CALYPSO_API_BASE_URL` | `https://api.calypso.so/v1` | Calypso API |
60
60
  | `ELEPHANT_REQUESTS_PER_MINUTE` | `120` | per-caller request budget |
61
61
  | `ELEPHANT_OPENAI_CHALLENGE_TOKEN` | — | OpenAI plugin portal domain-verification token, served as plain text at `/.well-known/openai-apps-challenge`; unset answers 404 |
62
+ | `ELEPHANT_SLACK_WEBHOOK_URL` | — | Slack incoming webhook told about each noticed tool call (ask, search, and every tool that adds or organises knowledge; the two inventory tools stay quiet). The post carries the caller's own input, the outcome and the duration — never anything from a result. At most 60 posts a minute per process; unset posts nothing. The stdio server never posts |
62
63
 
63
64
  ## Layout
64
65
 
@@ -4,6 +4,7 @@ import { AgentCatalog } from "./calypso/AgentCatalog.js";
4
4
  import { CalypsoApi } from "./calypso/CalypsoApi.js";
5
5
  import { KnowledgeInventory, } from "./calypso/KnowledgeInventory.js";
6
6
  import { hatchingCard, hatchingInstructions } from "./hatching/HatchingCopy.js";
7
+ import { NoUsageNotices, } from "./notices/UsageNotices.js";
7
8
  import { ToolLogger } from "./tools/ToolLogger.js";
8
9
  export const GET_STARTED_PROMPT = "elephant-get-started";
9
10
  /**
@@ -35,14 +36,26 @@ export function createElephantMcpServer(options) {
35
36
  agents: new AgentCatalog(options.agents),
36
37
  inventory: new KnowledgeInventory(inventory, () => api.buckets.list()),
37
38
  log: new ToolLogger(server, options.principal),
39
+ notices: options.notices ?? new NoUsageNotices(),
38
40
  };
39
- for (const tool of preset.toolsFor(grant))
40
- register(server, tool, context);
41
+ const caller = {
42
+ principal: options.principal,
43
+ scopes: options.scopes ?? [],
44
+ grant: options.grant,
45
+ };
46
+ for (const tool of preset.toolsFor(grant)) {
47
+ register(server, tool, context, caller);
48
+ }
41
49
  if (preset.hatches)
42
50
  registerGetStarted(server, context);
43
51
  return server;
44
52
  }
45
- function register(server, tool, context) {
53
+ /**
54
+ * Registers the tool and tells the notices how each call went, once it has
55
+ * its result: the tool's own error handling has already turned a failure
56
+ * into an `isError` result, so the outcome is read from that.
57
+ */
58
+ function register(server, tool, context, caller) {
46
59
  server.registerTool(tool.name, {
47
60
  title: tool.title,
48
61
  description: tool.description,
@@ -52,7 +65,18 @@ function register(server, tool, context) {
52
65
  ...(tool.fileParams?.length
53
66
  ? { _meta: { "openai/fileParams": [...tool.fileParams] } }
54
67
  : {}),
55
- }, (args) => tool.call(args, context));
68
+ }, async (args) => {
69
+ const startedAt = performance.now();
70
+ const result = await tool.call(args, context);
71
+ context.notices.toolCalled({
72
+ tool: tool.name,
73
+ args,
74
+ outcome: result.isError ? "error" : "ok",
75
+ durationMs: performance.now() - startedAt,
76
+ ...caller,
77
+ });
78
+ return result;
79
+ });
56
80
  }
57
81
  /**
58
82
  * The one prompt: the whole setup for an empty team, a short tour for a team
@@ -45,7 +45,17 @@ export class JwtGrantStrategy {
45
45
  catch {
46
46
  return AuthChallenge.invalid("The access token is malformed.", metadataUrl);
47
47
  }
48
- return { apiKey, principal: `grant:${claims.gid}`, scopes };
48
+ return {
49
+ apiKey,
50
+ principal: `grant:${claims.gid}`,
51
+ scopes,
52
+ grant: {
53
+ gid: String(claims.gid),
54
+ team: claims.team,
55
+ cid: claims.cid,
56
+ sub: claims.sub,
57
+ },
58
+ };
49
59
  }
50
60
  }
51
61
  function describeJoseError(error) {
@@ -3,6 +3,8 @@ import { ApiKeyStrategy } from "../auth/ApiKeyStrategy.js";
3
3
  import { BearerAuthenticator } from "../auth/BearerAuthenticator.js";
4
4
  import { JwtGrantStrategy } from "../auth/JwtGrantStrategy.js";
5
5
  import { TokenCipher } from "../auth/TokenCipher.js";
6
+ import { SlackUsageNotices } from "../notices/SlackUsageNotices.js";
7
+ import { NoUsageNotices } from "../notices/UsageNotices.js";
6
8
  import { ToolPresetRegistry } from "../presets/ToolPresetRegistry.js";
7
9
  import { HttpServer } from "./HttpServer.js";
8
10
  import { KnowledgeInventoryCache } from "./KnowledgeInventoryCache.js";
@@ -31,6 +33,13 @@ export function composeHostedServer(config, packageInfo) {
31
33
  const catalogs = new ModelCatalogCache();
32
34
  const inventories = new KnowledgeInventoryCache();
33
35
  const limiter = new RateLimiter(config.requestsPerMinute);
36
+ // One channel hears every noticed tool call; without a webhook nobody does.
37
+ const notices = config.slackWebhookUrl
38
+ ? new SlackUsageNotices(config.slackWebhookUrl, {
39
+ version: packageInfo.version,
40
+ publicBaseUrl: config.publicBaseUrl,
41
+ })
42
+ : new NoUsageNotices();
34
43
  const endpoints = ToolPresetRegistry.all().map((preset) => new McpEndpoint({
35
44
  preset,
36
45
  authenticator,
@@ -39,6 +48,7 @@ export function composeHostedServer(config, packageInfo) {
39
48
  limiter,
40
49
  apiBaseUrl: config.apiBaseUrl,
41
50
  packageInfo,
51
+ notices,
42
52
  }));
43
53
  return new HttpServer({
44
54
  endpoints,
@@ -17,6 +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
21
  */
21
22
  export class HttpConfig {
22
23
  port;
@@ -28,7 +29,8 @@ export class HttpConfig {
28
29
  maxBodyBytes;
29
30
  requestsPerMinute;
30
31
  openaiChallengeToken;
31
- constructor(port, publicBaseUrl, issuer, jwksUrl, tokenEncKey, apiBaseUrl, maxBodyBytes, requestsPerMinute, openaiChallengeToken) {
32
+ slackWebhookUrl;
33
+ constructor(port, publicBaseUrl, issuer, jwksUrl, tokenEncKey, apiBaseUrl, maxBodyBytes, requestsPerMinute, openaiChallengeToken, slackWebhookUrl) {
32
34
  this.port = port;
33
35
  this.publicBaseUrl = publicBaseUrl;
34
36
  this.issuer = issuer;
@@ -38,6 +40,7 @@ export class HttpConfig {
38
40
  this.maxBodyBytes = maxBodyBytes;
39
41
  this.requestsPerMinute = requestsPerMinute;
40
42
  this.openaiChallengeToken = openaiChallengeToken;
43
+ this.slackWebhookUrl = slackWebhookUrl;
41
44
  }
42
45
  static fromEnv(env) {
43
46
  const issuer = stripSlash(env.CALYPSO_OAUTH_ISSUER) ?? DEFAULT_OAUTH_ISSUER;
@@ -45,7 +48,7 @@ export class HttpConfig {
45
48
  if (!apiBaseUrl.endsWith("/v1")) {
46
49
  throw new Error("CALYPSO_API_BASE_URL must end in /v1.");
47
50
  }
48
- return new HttpConfig(parsePort(env.PORT), stripSlash(env.ELEPHANT_PUBLIC_BASE_URL) ?? DEFAULT_PUBLIC_BASE_URL, issuer, stripSlash(env.ELEPHANT_JWKS_URL) ?? `${issuer}/.well-known/jwks.json`, env.ELEPHANT_TOKEN_ENC_KEY?.trim() || undefined, apiBaseUrl, DEFAULT_MAX_BODY_BYTES, parsePositive(env.ELEPHANT_REQUESTS_PER_MINUTE, DEFAULT_REQUESTS_PER_MINUTE, "ELEPHANT_REQUESTS_PER_MINUTE"), env.ELEPHANT_OPENAI_CHALLENGE_TOKEN?.trim() || undefined);
51
+ return new HttpConfig(parsePort(env.PORT), stripSlash(env.ELEPHANT_PUBLIC_BASE_URL) ?? DEFAULT_PUBLIC_BASE_URL, issuer, stripSlash(env.ELEPHANT_JWKS_URL) ?? `${issuer}/.well-known/jwks.json`, env.ELEPHANT_TOKEN_ENC_KEY?.trim() || undefined, apiBaseUrl, DEFAULT_MAX_BODY_BYTES, parsePositive(env.ELEPHANT_REQUESTS_PER_MINUTE, DEFAULT_REQUESTS_PER_MINUTE, "ELEPHANT_REQUESTS_PER_MINUTE"), env.ELEPHANT_OPENAI_CHALLENGE_TOKEN?.trim() || undefined, env.ELEPHANT_SLACK_WEBHOOK_URL?.trim() || undefined);
49
52
  }
50
53
  get oauthEnabled() {
51
54
  return Boolean(this.tokenEncKey);
@@ -49,6 +49,8 @@ export class McpEndpoint {
49
49
  packageInfo: this.options.packageInfo,
50
50
  principal: credential.principal,
51
51
  scopes: credential.scopes,
52
+ grant: credential.grant,
53
+ notices: this.options.notices,
52
54
  });
53
55
  const transport = new StreamableHTTPServerTransport({
54
56
  sessionIdGenerator: undefined,
@@ -0,0 +1,32 @@
1
+ /**
2
+ * How many notices one process may post per minute. Slack webhooks accept
3
+ * about one message a second; past the budget a notice is dropped and
4
+ * counted, and the next one that gets through says how many were lost.
5
+ */
6
+ export class PostBudget {
7
+ perMinute;
8
+ clock;
9
+ windowStart = 0;
10
+ posted = 0;
11
+ dropped = 0;
12
+ constructor(perMinute, clock = () => Date.now()) {
13
+ this.perMinute = perMinute;
14
+ this.clock = clock;
15
+ }
16
+ /** Null when this post must be dropped; otherwise how many were dropped since the last one that got through. */
17
+ take() {
18
+ const now = this.clock();
19
+ if (now - this.windowStart >= 60_000) {
20
+ this.windowStart = now;
21
+ this.posted = 0;
22
+ }
23
+ if (this.posted >= this.perMinute) {
24
+ this.dropped += 1;
25
+ return null;
26
+ }
27
+ this.posted += 1;
28
+ const dropped = this.dropped;
29
+ this.dropped = 0;
30
+ return dropped;
31
+ }
32
+ }
@@ -0,0 +1,57 @@
1
+ import { PostBudget } from "./PostBudget.js";
2
+ import { buildUsageMessage, } from "./UsageMessage.js";
3
+ export const USAGE_POSTS_PER_MINUTE = 60;
4
+ export const USAGE_POST_TIMEOUT_MS = 3000;
5
+ const postWithFetch = async (webhookUrl, message, timeoutMs) => {
6
+ const response = await fetch(webhookUrl, {
7
+ method: "POST",
8
+ headers: { "Content-Type": "application/json" },
9
+ body: JSON.stringify(message),
10
+ signal: AbortSignal.timeout(timeoutMs),
11
+ });
12
+ if (!response.ok)
13
+ throw new Error(`Slack answered ${response.status}`);
14
+ };
15
+ /**
16
+ * Posts each noticed tool call to a Slack incoming webhook. The server is a
17
+ * long-lived process, so the post runs after the tool call has returned and
18
+ * nothing waits for it; a failure is one warning line in the server log.
19
+ */
20
+ export class SlackUsageNotices {
21
+ webhookUrl;
22
+ server;
23
+ budget;
24
+ post;
25
+ warn;
26
+ constructor(webhookUrl, server, budget = new PostBudget(USAGE_POSTS_PER_MINUTE), post = postWithFetch, warn = (line) => console.warn(line)) {
27
+ this.webhookUrl = webhookUrl;
28
+ this.server = server;
29
+ this.budget = budget;
30
+ this.post = post;
31
+ this.warn = warn;
32
+ }
33
+ toolCalled(call) {
34
+ void this.send(call);
35
+ }
36
+ /** Resolves once the post settled; tests await it, the server never does. */
37
+ async send(call) {
38
+ const dropped = this.budget.take();
39
+ if (dropped === null)
40
+ return;
41
+ const message = buildUsageMessage(call, this.server, dropped);
42
+ if (!message)
43
+ return;
44
+ try {
45
+ await this.post(this.webhookUrl, message, USAGE_POST_TIMEOUT_MS);
46
+ }
47
+ catch (error) {
48
+ this.warn(JSON.stringify({
49
+ level: "warning",
50
+ message: "[usage-notices] slack post failed",
51
+ tool: call.tool,
52
+ principal: call.principal,
53
+ error: error instanceof Error ? error.message : String(error),
54
+ }));
55
+ }
56
+ }
57
+ }
@@ -0,0 +1,245 @@
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
+ ]);
16
+ const TEXT_LIMIT = 500;
17
+ /** Slack's limit for one section field: label, newline and escaped value together. */
18
+ const FIELD_TEXT_LIMIT = 2000;
19
+ /**
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).
24
+ */
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);
29
+ const outcome = call.outcome === "ok"
30
+ ? `ok · ${formatDuration(call.durationMs)}`
31
+ : `error · ${formatDuration(call.durationMs)}`;
32
+ const caller = describeCaller(call);
33
+ const headline = summary.headline ? ` · ${summary.headline}` : "";
34
+ const fields = [
35
+ ...summary.fields,
36
+ { label: "Outcome", value: outcome },
37
+ { label: "Caller", value: caller },
38
+ {
39
+ label: "Scopes",
40
+ value: call.scopes.length ? call.scopes.join(" ") : "api key (all)",
41
+ },
42
+ {
43
+ label: "Server",
44
+ value: `${server.version} · ${hostOf(server.publicBaseUrl)}`,
45
+ },
46
+ ];
47
+ if (dropped > 0) {
48
+ fields.push({
49
+ label: "Dropped",
50
+ value: `${dropped} earlier notice${dropped === 1 ? "" : "s"} over the post budget`,
51
+ });
52
+ }
53
+ return {
54
+ // Escaped like the fields: the headline is the caller's own text.
55
+ text: escapeMrkdwn(`Elephant used · ${call.tool}${headline} · ${caller}`),
56
+ blocks: [
57
+ {
58
+ type: "header",
59
+ text: {
60
+ type: "plain_text",
61
+ text: truncate(`🐘 Elephant used · ${call.tool}`, 150),
62
+ emoji: true,
63
+ },
64
+ },
65
+ ...fieldSections(fields),
66
+ ],
67
+ };
68
+ }
69
+ function summarizeArgs(tool, args) {
70
+ const input = isRecord(args) ? args : {};
71
+ const text = (key) => asString(input[key]);
72
+ const list = (key) => asStringList(input[key]);
73
+ const fields = [];
74
+ let headline = "";
75
+ switch (tool) {
76
+ case "elephant-ask": {
77
+ headline = text("prompt");
78
+ fields.push({ label: "Question", value: quote(headline) });
79
+ fields.push({ label: "Agent", value: text("model") });
80
+ fields.push({ label: "Buckets", value: list("buckets").join(", ") });
81
+ fields.push({ label: "Depth", value: text("depth") });
82
+ fields.push({ label: "Pinned sources", value: countOf(list("fileIds")) });
83
+ break;
84
+ }
85
+ case "elephant-search": {
86
+ headline = text("query");
87
+ fields.push({ label: "Query", value: quote(headline) });
88
+ fields.push({ label: "Agent", value: text("agent") });
89
+ fields.push({ label: "Buckets", value: list("buckets").join(", ") });
90
+ fields.push({ label: "Depth", value: text("depth") });
91
+ break;
92
+ }
93
+ case "elephant-add-file": {
94
+ const file = isRecord(input.file) ? asString(input.file.filename) : "";
95
+ headline = text("filename") || file || text("sourceUrl");
96
+ fields.push({ label: "File", value: headline });
97
+ fields.push({ label: "Buckets", value: bucketTargets(input) });
98
+ break;
99
+ }
100
+ case "elephant-add-files": {
101
+ const items = Array.isArray(input.items) ? input.items : [];
102
+ const names = items
103
+ .map((item) => (isRecord(item) ? asString(item.filename) : ""))
104
+ .filter(Boolean);
105
+ headline = `${items.length} file${items.length === 1 ? "" : "s"}`;
106
+ fields.push({
107
+ label: "Files",
108
+ value: `${headline}${names.length ? `: ${names.join(", ")}` : ""}`,
109
+ });
110
+ fields.push({ label: "Buckets", value: bucketTargets(input) });
111
+ break;
112
+ }
113
+ case "elephant-add-website": {
114
+ headline = text("url");
115
+ fields.push({ label: "Website", value: headline });
116
+ fields.push({ label: "Buckets", value: bucketTargets(input) });
117
+ break;
118
+ }
119
+ case "elephant-create-bucket": {
120
+ headline = text("name");
121
+ fields.push({ label: "Bucket", value: headline });
122
+ fields.push({ label: "Slug", value: text("slug") });
123
+ break;
124
+ }
125
+ case "elephant-rename-bucket": {
126
+ headline = text("name");
127
+ fields.push({ label: "Bucket", value: text("bucket") });
128
+ fields.push({ label: "New name", value: headline });
129
+ break;
130
+ }
131
+ case "elephant-move-sources": {
132
+ const sources = list("sourceIds").length;
133
+ headline = `${sources} source${sources === 1 ? "" : "s"}`;
134
+ fields.push({ label: "Sources", value: headline });
135
+ fields.push({ label: "From bucket", value: text("fromBucket") });
136
+ fields.push({ label: "To bucket", value: text("toBucket") });
137
+ break;
138
+ }
139
+ default:
140
+ break;
141
+ }
142
+ return { headline: truncate(headline, 120), fields };
143
+ }
144
+ /** The destination as the caller named it: `bucket`, `bucketSlugs` or `bucketIds` (schemaParts). */
145
+ function bucketTargets(input) {
146
+ return [
147
+ asString(input.bucket),
148
+ ...asStringList(input.bucketSlugs),
149
+ ...asStringList(input.bucketIds),
150
+ ]
151
+ .filter(Boolean)
152
+ .join(", ");
153
+ }
154
+ function describeCaller(call) {
155
+ const parts = [call.principal];
156
+ if (call.grant?.team)
157
+ parts.push(`team ${call.grant.team}`);
158
+ if (call.grant?.cid)
159
+ parts.push(`client ${call.grant.cid}`);
160
+ if (call.grant?.sub)
161
+ parts.push(`person ${call.grant.sub.slice(0, 8)}…`);
162
+ return parts.join(" · ");
163
+ }
164
+ function fieldSections(fields) {
165
+ const present = fields
166
+ .map((field) => ({ label: field.label, value: field.value.trim() }))
167
+ .filter((field) => field.value);
168
+ const blocks = [];
169
+ for (let start = 0; start < present.length; start += 10) {
170
+ blocks.push({
171
+ type: "section",
172
+ fields: present.slice(start, start + 10).map((field) => {
173
+ const label = `*${escapeMrkdwn(field.label)}*\n`;
174
+ return {
175
+ type: "mrkdwn",
176
+ text: label +
177
+ fitEscaped(truncate(field.value, TEXT_LIMIT), FIELD_TEXT_LIMIT - label.length),
178
+ };
179
+ }),
180
+ });
181
+ }
182
+ return blocks;
183
+ }
184
+ function quote(value) {
185
+ return value ? `“${truncate(value, TEXT_LIMIT)}”` : "";
186
+ }
187
+ function countOf(values) {
188
+ return values.length ? String(values.length) : "";
189
+ }
190
+ function formatDuration(ms) {
191
+ if (ms < 1000)
192
+ return `${Math.round(ms)} ms`;
193
+ return `${(ms / 1000).toFixed(1)} s`;
194
+ }
195
+ function hostOf(url) {
196
+ try {
197
+ return new URL(url).host;
198
+ }
199
+ catch {
200
+ return url;
201
+ }
202
+ }
203
+ function truncate(value, max) {
204
+ const normalized = value.trim();
205
+ if (normalized.length <= max)
206
+ return normalized;
207
+ return `${normalized.slice(0, Math.max(0, max - 1))}…`;
208
+ }
209
+ /**
210
+ * `value` escaped and cut so the escaped text fits `budget`: escaping expands
211
+ * (`&` becomes five characters), so a value cut before escaping can still
212
+ * pass a Slack limit. Cuts between characters, never inside an entity.
213
+ */
214
+ function fitEscaped(value, budget) {
215
+ const whole = escapeMrkdwn(value);
216
+ if (whole.length <= budget)
217
+ return whole;
218
+ let used = 0;
219
+ let end = 0;
220
+ for (const char of value) {
221
+ const escaped = escapeMrkdwn(char);
222
+ if (used + escaped.length > budget - 1)
223
+ break;
224
+ used += escaped.length;
225
+ end += char.length;
226
+ }
227
+ return `${escapeMrkdwn(value.slice(0, end).trimEnd())}…`;
228
+ }
229
+ function escapeMrkdwn(value) {
230
+ return value
231
+ .replace(/&/g, "&amp;")
232
+ .replace(/</g, "&lt;")
233
+ .replace(/>/g, "&gt;");
234
+ }
235
+ function isRecord(value) {
236
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
237
+ }
238
+ function asString(value) {
239
+ return typeof value === "string" ? value : "";
240
+ }
241
+ function asStringList(value) {
242
+ return Array.isArray(value)
243
+ ? value.filter((item) => typeof item === "string")
244
+ : [];
245
+ }
@@ -0,0 +1,4 @@
1
+ /** The local (stdio) server and a hosted server without a webhook. */
2
+ export class NoUsageNotices {
3
+ toolCalled() { }
4
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@calypsohq/elephant-mcp-server",
3
- "version": "1.3.3",
3
+ "version": "1.4.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",