@calypsohq/elephant-mcp-server 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -2
  3. package/dist/ElephantMcpServer.js +73 -0
  4. package/dist/auth/ApiKeyStrategy.js +21 -0
  5. package/dist/auth/AuthChallenge.js +53 -0
  6. package/dist/auth/AuthStrategy.js +1 -0
  7. package/dist/auth/BearerAuthenticator.js +30 -0
  8. package/dist/auth/Credential.js +1 -0
  9. package/dist/auth/JwtGrantStrategy.js +58 -0
  10. package/dist/auth/TokenCipher.js +48 -0
  11. package/dist/calypso/AgentCatalog.js +29 -0
  12. package/dist/calypso/AgentCatalogLoader.js +117 -0
  13. package/dist/calypso/AgentResponses.js +94 -0
  14. package/dist/calypso/BatchManifest.js +105 -0
  15. package/dist/calypso/BucketDestination.js +26 -0
  16. package/dist/calypso/CalypsoApi.js +32 -0
  17. package/dist/calypso/CalypsoApiClient.js +44 -0
  18. package/dist/calypso/CalypsoApiConfig.js +9 -0
  19. package/dist/calypso/KnowledgeBatches.js +122 -0
  20. package/dist/calypso/KnowledgeBuckets.js +30 -0
  21. package/dist/calypso/KnowledgeFiles.js +147 -0
  22. package/dist/calypso/KnowledgeInventory.js +68 -0
  23. package/dist/calypso/KnowledgeSearch.js +34 -0
  24. package/dist/calypso/KnowledgeWebsites.js +49 -0
  25. package/dist/calypso/UploadContent.js +33 -0
  26. package/dist/calypso/apiErrors.js +59 -0
  27. package/dist/calypso/bucketList.js +77 -0
  28. package/dist/calypso/coerce.js +31 -0
  29. package/dist/calypso/knowledgeTypes.js +8 -0
  30. package/dist/calypso/polling.js +26 -0
  31. package/dist/calypso/uploadBytes.js +23 -0
  32. package/dist/hatching/HatchingCopy.js +76 -0
  33. package/dist/http/HostedServer.js +50 -0
  34. package/dist/http/HttpConfig.js +72 -0
  35. package/dist/http/HttpServer.js +126 -0
  36. package/dist/http/KnowledgeInventoryCache.js +47 -0
  37. package/dist/http/McpEndpoint.js +83 -0
  38. package/dist/http/ModelCatalogCache.js +45 -0
  39. package/dist/http/ProtectedResourceMetadata.js +40 -0
  40. package/dist/http/RateLimiter.js +56 -0
  41. package/dist/index.js +27 -0
  42. package/dist/presets/ToolPreset.js +40 -0
  43. package/dist/presets/ToolPresetRegistry.js +56 -0
  44. package/dist/stdio/LocalPresets.js +37 -0
  45. package/dist/stdio/StdioOptions.js +61 -0
  46. package/dist/stdio.js +56 -0
  47. package/dist/tools/AddFileTool.js +104 -0
  48. package/dist/tools/AddFilesTool.js +81 -0
  49. package/dist/tools/AddWebsiteTool.js +56 -0
  50. package/dist/tools/AskTool.js +69 -0
  51. package/dist/tools/CreateBucketTool.js +61 -0
  52. package/dist/tools/ElephantTool.js +41 -0
  53. package/dist/tools/ListBucketsTool.js +35 -0
  54. package/dist/tools/OpenSourceTool.js +32 -0
  55. package/dist/tools/SearchTool.js +60 -0
  56. package/dist/tools/ToolContext.js +1 -0
  57. package/dist/tools/ToolLogger.js +29 -0
  58. package/dist/tools/schemaParts.js +46 -0
  59. package/package.json +61 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Calypso
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # Elephant MCP server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The MCP server for Elephant by Calypso, in two shapes from one codebase:
4
+
5
+ - **Hosted**: stateless, one process serves both plugins over Streamable HTTP with OAuth (`dist/index.js`, deployed at `mcp.calypso.so`).
6
+ - **Local**: `elephant-mcp` on stdio for one API key, published to npm as `@calypsohq/elephant-mcp-server` (`dist/stdio.js`).
7
+
8
+ ## Local (stdio)
9
+
10
+ ```bash
11
+ CALYPSO_API_KEY=sk-… npx -y @calypsohq/elephant-mcp-server [--preset all|elephant|elephant-builder]
12
+ ```
13
+
14
+ | Env | Default | Purpose |
15
+ |---|---|---|
16
+ | `CALYPSO_API_KEY` | — | the caller's Calypso API key (required; env only, never a flag) |
17
+ | `CALYPSO_API_BASE_URL` | `https://api.calypso.so/v1` | Calypso API |
18
+ | `ELEPHANT_PRESET` | `all` | default for `--preset` |
19
+
20
+ `all` publishes both tool sets under the `elephant` server name and hatches like Elephant; it exists only locally, the registry never serves it over HTTP. Discovery and the knowledge inventory load once at startup. Nothing of ours writes to stdout, which belongs to the protocol; `--help` and `--version` answer on stderr.
21
+
22
+ ## Endpoints
23
+
24
+ | Path | Purpose |
25
+ |---|---|
26
+ | `POST /elephant/mcp` | Elephant (read-only tools) |
27
+ | `POST /elephant/builder/mcp` | Elephant Builder (add/create tools) |
28
+ | `GET /.well-known/oauth-protected-resource/elephant/mcp` | RFC 9728 metadata for Elephant |
29
+ | `GET /.well-known/oauth-protected-resource/elephant/builder/mcp` | RFC 9728 metadata for Elephant Builder |
30
+ | `GET /healthz` | `{ ok, version }` |
31
+
32
+ `GET` and `DELETE` on an MCP path answer 405: there are no server-side sessions and no SSE resumption. Every `POST` builds a fresh server bound to the caller's credential, so any instance can serve any request.
33
+
34
+ ## Authentication
35
+
36
+ - **OAuth access token** from `login.calypso.so`: ES256 JWT, `aud` = the endpoint URL, `scope` = `elephant:read` or `elephant:write`, and an `ek` claim holding the grant's Calypso API key sealed with AES-256-GCM (`base64url(iv) "." base64url(ciphertext‖tag)`). A token for one endpoint is refused on the other.
37
+ - **Calypso API key** (`Authorization: Bearer sk-…`), for testing and clients that cannot do OAuth. Header only, never in the URL.
38
+
39
+ An unauthenticated request gets `401` with `WWW-Authenticate: Bearer resource_metadata="…"`, which is how ChatGPT discovers sign-in.
40
+
41
+ ## Configuration
42
+
43
+ | Env | Default | Purpose |
44
+ |---|---|---|
45
+ | `PORT` | `8080` | listen port |
46
+ | `ELEPHANT_PUBLIC_BASE_URL` | `https://mcp.calypso.so` | public origin; each endpoint's OAuth audience |
47
+ | `CALYPSO_OAUTH_ISSUER` | `https://login.calypso.so` | authorization server |
48
+ | `ELEPHANT_JWKS_URL` | `<issuer>/.well-known/jwks.json` | token signing keys |
49
+ | `ELEPHANT_TOKEN_ENC_KEY` | — | 32-byte base64 key shared with the authorization server; unset turns OAuth off (API keys only) |
50
+ | `CALYPSO_API_BASE_URL` | `https://api.calypso.so/v1` | Calypso API |
51
+ | `ELEPHANT_REQUESTS_PER_MINUTE` | `120` | per-caller request budget |
52
+
53
+ ## Layout
54
+
55
+ ```
56
+ src/
57
+ index.ts hosted entry point: reads HttpConfig, composes and starts the HTTP server
58
+ stdio.ts local entry point (`elephant-mcp`): one server over stdio for the key in the env
59
+ stdio/ StdioOptions (flags + env) and LocalPresets (`all`, the local-only preset)
60
+ ElephantMcpServer.ts builds one MCP server for one preset and one caller
61
+ tools/ one class per tool, each owning its name, wording and inputs
62
+ ElephantTool.ts base class: call() turns failures into readable tool errors
63
+ AskTool, SearchTool, ListBucketsTool, OpenSourceTool (Elephant)
64
+ AddFileTool, AddFilesTool, AddWebsiteTool, CreateBucketTool (Elephant Builder)
65
+ ToolContext.ts, ToolLogger.ts, schemaParts.ts
66
+ presets/ ToolPreset + ToolPresetRegistry: each plugin's path, scope and tools
67
+ calypso/ the Calypso API as one caller sees it (CalypsoApi groups the resources:
68
+ AgentResponses, KnowledgeSearch, KnowledgeBuckets, KnowledgeFiles,
69
+ KnowledgeBatches, KnowledgeWebsites) plus agent discovery
70
+ auth/ BearerAuthenticator + ApiKeyStrategy, JwtGrantStrategy, TokenCipher, AuthChallenge
71
+ http/ HttpServer, McpEndpoint, ProtectedResourceMetadata, ModelCatalogCache,
72
+ RateLimiter, HttpConfig, HostedServer (composition root)
73
+ ```
74
+
75
+ Each request builds a fresh `ElephantMcpServer` bound to the caller's key, so tools hold no state between calls. `elephant-ask` is stateless too: every question is its own conversation, and a follow-up must carry its subject in the prompt.
76
+
77
+ Uploads take a ChatGPT attachment (`file`, declared in `_meta["openai/fileParams"]`), a public `sourceUrl`, or `contentBase64`. An attachment's temporary download link is handed to Calypso to import, so the bytes never pass through this server. Nothing reads from the server's disk.
78
+
79
+ Each caller (grant or API key) gets `ELEPHANT_REQUESTS_PER_MINUTE` requests per minute across both endpoints (default 120); over that, `429` with `Retry-After`.
80
+
81
+ ## Commands
82
+
83
+ ```bash
84
+ npm ci
85
+ npm test # build + node --test
86
+ npm run lint
87
+ npm run smoke # spawns the HTTP server locally and probes discovery, challenges, 405s
88
+ npm run smoke:stdio # spawns elephant-mcp per preset and checks tools/list
89
+ SMOKE_API_KEY=sk-… npm run smoke:stdio # same, plus a real elephant-list-buckets call
90
+ SMOKE_BASE_URL=https://mcp.calypso.so SMOKE_API_KEY=sk-… npm run smoke # probe a deployment, including tools/list
91
+ npm start # node dist/index.js
92
+ ```
93
+
94
+ Deployment is described by [`../render.yaml`](../render.yaml) (service `elephant-mcp`, manual deploys). The npm package publishes from [`../.github/workflows/publish.yml`](../.github/workflows/publish.yml) on push to `main` when the version is new; `prepublishOnly` runs lint, typecheck, tests and the stdio smoke first.
@@ -0,0 +1,73 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { AgentCatalog } from "./calypso/AgentCatalog.js";
3
+ import { CalypsoApi } from "./calypso/CalypsoApi.js";
4
+ import { KnowledgeInventory, } from "./calypso/KnowledgeInventory.js";
5
+ import { hatchingCard, hatchingInstructions } from "./hatching/HatchingCopy.js";
6
+ import { ToolLogger } from "./tools/ToolLogger.js";
7
+ export const GET_STARTED_PROMPT = "elephant-get-started";
8
+ /**
9
+ * Builds the MCP server for one preset and one caller.
10
+ *
11
+ * Built per request and thrown away after it: the tools close over this
12
+ * caller's API client only, so nothing one caller does can reach another.
13
+ * A hatching preset chooses its `instructions` by the team's inventory and
14
+ * publishes the `elephant-get-started` prompt.
15
+ */
16
+ export function createElephantMcpServer(options) {
17
+ const { preset, packageInfo } = options;
18
+ const inventory = preset.hatches ? (options.inventory ?? null) : null;
19
+ const server = new McpServer({
20
+ name: preset.serverName,
21
+ title: preset.displayName,
22
+ version: packageInfo.version,
23
+ }, {
24
+ capabilities: { logging: {} },
25
+ instructions: preset.hatches
26
+ ? hatchingInstructions(preset.instructions, inventory)
27
+ : preset.instructions,
28
+ });
29
+ const api = new CalypsoApi(options.api, `${packageInfo.name}/${packageInfo.version} (Node.js/${process.versions.node})`);
30
+ const context = {
31
+ api,
32
+ agents: new AgentCatalog(options.agents),
33
+ inventory: new KnowledgeInventory(inventory, () => api.buckets.list()),
34
+ log: new ToolLogger(server, options.principal),
35
+ };
36
+ for (const tool of preset.tools)
37
+ register(server, tool, context);
38
+ if (preset.hatches)
39
+ registerGetStarted(server, context);
40
+ return server;
41
+ }
42
+ function register(server, tool, context) {
43
+ server.registerTool(tool.name, {
44
+ title: tool.title,
45
+ description: tool.description,
46
+ inputSchema: tool.inputSchema,
47
+ ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
48
+ annotations: tool.annotations,
49
+ ...(tool.fileParams?.length
50
+ ? { _meta: { "openai/fileParams": [...tool.fileParams] } }
51
+ : {}),
52
+ }, (args) => tool.call(args, context));
53
+ }
54
+ /**
55
+ * The one prompt: the whole setup for an empty team, a short tour for a team
56
+ * with knowledge. Clients show it as a slash command or a starter.
57
+ */
58
+ function registerGetStarted(server, context) {
59
+ server.registerPrompt(GET_STARTED_PROMPT, {
60
+ title: "Get started with Elephant",
61
+ description: "What Elephant can do for this team right now, and the next step: add a first source, or try a question.",
62
+ }, async () => ({
63
+ messages: [
64
+ {
65
+ role: "user",
66
+ content: {
67
+ type: "text",
68
+ text: hatchingCard(await context.inventory.current()),
69
+ },
70
+ },
71
+ ],
72
+ }));
73
+ }
@@ -0,0 +1,21 @@
1
+ const API_KEY_SHAPE = /^sk-[A-Za-z0-9_-]{16,}$/;
2
+ /**
3
+ * `Authorization: Bearer sk-…` — a Calypso project API key, passed through.
4
+ *
5
+ * The Calypso API is the authority on whether the key is valid and what it may do, so
6
+ * this strategy only checks the shape; a bad key fails on the first tool call
7
+ * with the API's own error. Keys are accepted only in the header, never in the
8
+ * URL, so they stay out of access logs.
9
+ */
10
+ export class ApiKeyStrategy {
11
+ accepts(token) {
12
+ return API_KEY_SHAPE.test(token);
13
+ }
14
+ async authenticate(token) {
15
+ return {
16
+ apiKey: token,
17
+ principal: `key:sk-…${token.slice(-4)}`,
18
+ scopes: [],
19
+ };
20
+ }
21
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * A refused request, rendered as RFC 6750 / RFC 9728 response.
3
+ *
4
+ * The `resource_metadata` parameter is what lets ChatGPT discover the
5
+ * authorization server from a bare 401, so every challenge on an OAuth
6
+ * preset must carry it.
7
+ */
8
+ export class AuthChallenge {
9
+ status;
10
+ error;
11
+ description;
12
+ resourceMetadataUrl;
13
+ scope;
14
+ constructor(status, error, description, resourceMetadataUrl, scope) {
15
+ this.status = status;
16
+ this.error = error;
17
+ this.description = description;
18
+ this.resourceMetadataUrl = resourceMetadataUrl;
19
+ this.scope = scope;
20
+ }
21
+ static missing(resourceMetadataUrl) {
22
+ return new AuthChallenge(401, undefined, "Authentication required.", resourceMetadataUrl, undefined);
23
+ }
24
+ static invalid(description, resourceMetadataUrl) {
25
+ return new AuthChallenge(401, "invalid_token", description, resourceMetadataUrl, undefined);
26
+ }
27
+ static insufficientScope(scope, resourceMetadataUrl) {
28
+ return new AuthChallenge(403, "insufficient_scope", `This endpoint requires the ${scope} scope.`, resourceMetadataUrl, scope);
29
+ }
30
+ /** Value of the `WWW-Authenticate` response header. */
31
+ header() {
32
+ const params = [];
33
+ if (this.resourceMetadataUrl) {
34
+ params.push(`resource_metadata="${this.resourceMetadataUrl}"`);
35
+ }
36
+ else {
37
+ params.push('realm="calypso"');
38
+ }
39
+ if (this.error) {
40
+ params.push(`error="${this.error}"`);
41
+ params.push(`error_description="${this.description}"`);
42
+ }
43
+ if (this.scope)
44
+ params.push(`scope="${this.scope}"`);
45
+ return `Bearer ${params.join(", ")}`;
46
+ }
47
+ body() {
48
+ return {
49
+ error: this.error ?? "unauthorized",
50
+ error_description: this.description,
51
+ };
52
+ }
53
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import { AuthChallenge } from "./AuthChallenge.js";
2
+ /**
3
+ * Picks the strategy that recognizes the bearer token and runs it.
4
+ *
5
+ * No token, or one no strategy recognizes, yields the 401 that starts OAuth
6
+ * discovery for presets that support it.
7
+ */
8
+ export class BearerAuthenticator {
9
+ strategies;
10
+ resourceMetadataUrl;
11
+ constructor(strategies, resourceMetadataUrl) {
12
+ this.strategies = strategies;
13
+ this.resourceMetadataUrl = resourceMetadataUrl;
14
+ }
15
+ async authenticate(authorization, preset) {
16
+ const metadataUrl = this.resourceMetadataUrl(preset);
17
+ const token = BearerAuthenticator.bearerToken(authorization);
18
+ if (!token)
19
+ return AuthChallenge.missing(metadataUrl);
20
+ const strategy = this.strategies.find((item) => item.accepts(token));
21
+ if (!strategy) {
22
+ return AuthChallenge.invalid("Unrecognized bearer token.", metadataUrl);
23
+ }
24
+ return strategy.authenticate(token, preset);
25
+ }
26
+ static bearerToken(authorization) {
27
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization ?? "");
28
+ return match?.[1];
29
+ }
30
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,58 @@
1
+ import { errors, jwtVerify } from "jose";
2
+ import { AuthChallenge } from "./AuthChallenge.js";
3
+ const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
4
+ /**
5
+ * Access tokens issued by the Elephant authorization server (login.calypso.so).
6
+ *
7
+ * Verifies signature, issuer, audience (exactly this preset's URL — a token
8
+ * for /elephant/mcp is useless on /elephant/builder/mcp), expiry and scope,
9
+ * then unseals the grant's API key from `ek`. The server keeps no grant state:
10
+ * revoking a grant revokes its key, which the Calypso API then rejects.
11
+ */
12
+ export class JwtGrantStrategy {
13
+ options;
14
+ constructor(options) {
15
+ this.options = options;
16
+ }
17
+ accepts(token) {
18
+ return JWT_SHAPE.test(token);
19
+ }
20
+ async authenticate(token, preset) {
21
+ const metadataUrl = this.options.resourceMetadataUrl(preset);
22
+ let claims;
23
+ try {
24
+ const verified = await jwtVerify(token, this.options.keys, {
25
+ issuer: this.options.issuer,
26
+ audience: preset.resourceUrl(this.options.publicBaseUrl),
27
+ algorithms: ["ES256"],
28
+ requiredClaims: ["exp", "sub", "gid", "ek"],
29
+ });
30
+ claims = verified.payload;
31
+ }
32
+ catch (error) {
33
+ return AuthChallenge.invalid(describeJoseError(error), metadataUrl);
34
+ }
35
+ const scopes = String(claims.scope ?? "")
36
+ .split(" ")
37
+ .filter(Boolean);
38
+ if (!scopes.includes(preset.scope)) {
39
+ return AuthChallenge.insufficientScope(preset.scope, metadataUrl);
40
+ }
41
+ let apiKey;
42
+ try {
43
+ apiKey = this.options.cipher.open(String(claims.ek));
44
+ }
45
+ catch {
46
+ return AuthChallenge.invalid("The access token is malformed.", metadataUrl);
47
+ }
48
+ return { apiKey, principal: `grant:${claims.gid}`, scopes };
49
+ }
50
+ }
51
+ function describeJoseError(error) {
52
+ if (error instanceof errors.JWTExpired)
53
+ return "The access token expired.";
54
+ if (error instanceof errors.JWTClaimValidationFailed) {
55
+ return `The access token is not valid here (${error.claim}).`;
56
+ }
57
+ return "The access token is invalid.";
58
+ }
@@ -0,0 +1,48 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
+ const ALGORITHM = "aes-256-gcm";
3
+ const IV_BYTES = 12;
4
+ const TAG_BYTES = 16;
5
+ /**
6
+ * AES-256-GCM sealing for the `ek` access-token claim.
7
+ *
8
+ * Wire format (shared with the authorization server in web-app-new):
9
+ * `base64url(iv[12]) "." base64url(ciphertext ‖ tag[16])`.
10
+ * The key is 32 bytes, configured base64-encoded in ELEPHANT_TOKEN_ENC_KEY.
11
+ */
12
+ export class TokenCipher {
13
+ key;
14
+ constructor(base64Key) {
15
+ const key = Buffer.from(base64Key, "base64");
16
+ if (key.length !== 32) {
17
+ throw new Error("ELEPHANT_TOKEN_ENC_KEY must be 32 bytes, base64-encoded.");
18
+ }
19
+ this.key = key;
20
+ }
21
+ seal(plaintext) {
22
+ const iv = randomBytes(IV_BYTES);
23
+ const cipher = createCipheriv(ALGORITHM, this.key, iv);
24
+ const body = Buffer.concat([
25
+ cipher.update(plaintext, "utf8"),
26
+ cipher.final(),
27
+ cipher.getAuthTag(),
28
+ ]);
29
+ return `${iv.toString("base64url")}.${body.toString("base64url")}`;
30
+ }
31
+ open(sealed) {
32
+ const [ivPart, bodyPart, ...rest] = sealed.split(".");
33
+ if (!ivPart || !bodyPart || rest.length > 0) {
34
+ throw new Error("Malformed sealed value.");
35
+ }
36
+ const iv = Buffer.from(ivPart, "base64url");
37
+ const body = Buffer.from(bodyPart, "base64url");
38
+ if (iv.length !== IV_BYTES || body.length <= TAG_BYTES) {
39
+ throw new Error("Malformed sealed value.");
40
+ }
41
+ const decipher = createDecipheriv(ALGORITHM, this.key, iv);
42
+ decipher.setAuthTag(body.subarray(body.length - TAG_BYTES));
43
+ return Buffer.concat([
44
+ decipher.update(body.subarray(0, body.length - TAG_BYTES)),
45
+ decipher.final(),
46
+ ]).toString("utf8");
47
+ }
48
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The agents a caller may ask, and which one answers by default.
3
+ *
4
+ * Tools read the catalog through this accessor rather than the raw snapshot so
5
+ * the rule "only ids discovery lists are accepted" lives in one place. An
6
+ * unknown id fails loudly and names the alternatives, which lets the model
7
+ * correct itself instead of the API answering with an opaque 404.
8
+ */
9
+ export class AgentCatalog {
10
+ snapshot;
11
+ constructor(snapshot) {
12
+ this.snapshot = snapshot;
13
+ }
14
+ get defaultAgentId() {
15
+ return this.snapshot.defaultModel;
16
+ }
17
+ ids() {
18
+ return this.snapshot.models.map((agent) => agent.id);
19
+ }
20
+ /** The requested agent id, or the default when none was requested. */
21
+ resolve(requested) {
22
+ const agentId = String(requested || "").trim() || this.defaultAgentId;
23
+ const known = this.ids();
24
+ if (!known.includes(agentId)) {
25
+ throw new Error(`Unknown agent \`${agentId}\`. Available: ${known.join(", ")}.`);
26
+ }
27
+ return agentId;
28
+ }
29
+ }
@@ -0,0 +1,117 @@
1
+ import { CalypsoApiClient } from "./CalypsoApiClient.js";
2
+ import { asRecord, numberOrUndefined, trimmedString, uniqueStrings, } from "./coerce.js";
3
+ /**
4
+ * Id of the agent every Calypso team has. It is an API model id (data the
5
+ * Calypso API defines; `elephant-agent` since Step 2 of the Elephant rename,
6
+ * 2026-11-17), used only so asking still works when discovery is
7
+ * unreachable; it is never part of anything a client reads.
8
+ */
9
+ const BASE_AGENT_ID = "elephant-agent";
10
+ // Discovery runs on the request path of every cold cache entry, so it gets a
11
+ // short budget: a slow answer must degrade to the fallback, not stall a call.
12
+ const DISCOVERY_TIMEOUT_MS = 2000;
13
+ function baseAgent() {
14
+ return {
15
+ id: BASE_AGENT_ID,
16
+ base_model: BASE_AGENT_ID,
17
+ profile_id: null,
18
+ source: "default_policy",
19
+ enabled: true,
20
+ bucket_ids: [],
21
+ buckets: [],
22
+ missing_bucket_ids: [],
23
+ };
24
+ }
25
+ /** The catalog used when discovery cannot be reached: the base agent alone. */
26
+ export function fallbackAgentCatalog(error) {
27
+ return {
28
+ models: [baseAgent()],
29
+ defaultModel: BASE_AGENT_ID,
30
+ fetchedAt: null,
31
+ source: "fallback",
32
+ error: error instanceof Error
33
+ ? error.message
34
+ : error
35
+ ? String(error)
36
+ : undefined,
37
+ };
38
+ }
39
+ /**
40
+ * Loads the team's agents from `GET /rag-agent/models`.
41
+ *
42
+ * Never rejects: any failure (no key, timeout, non-2xx, malformed body)
43
+ * yields the fallback catalog, because a discovery outage must not take the
44
+ * tools down with it.
45
+ */
46
+ export async function loadAgentCatalog(config) {
47
+ if (!String(config.apiKey || "").trim()) {
48
+ return fallbackAgentCatalog("No Calypso API key on the request.");
49
+ }
50
+ const controller = new AbortController();
51
+ const timeout = setTimeout(() => controller.abort(), DISCOVERY_TIMEOUT_MS);
52
+ try {
53
+ const body = await new CalypsoApiClient(config).request("/rag-agent/models", { method: "GET", signal: controller.signal });
54
+ return normalizeCatalog(body);
55
+ }
56
+ catch (error) {
57
+ return fallbackAgentCatalog(error);
58
+ }
59
+ finally {
60
+ clearTimeout(timeout);
61
+ }
62
+ }
63
+ function normalizeCatalog(body) {
64
+ const data = asRecord(body)?.data;
65
+ const byId = new Map();
66
+ for (const item of Array.isArray(data) ? data : []) {
67
+ const agent = normalizeAgent(item);
68
+ if (agent && !byId.has(agent.id))
69
+ byId.set(agent.id, agent);
70
+ }
71
+ const models = [...byId.values()];
72
+ if (!byId.has(BASE_AGENT_ID))
73
+ models.unshift(baseAgent());
74
+ // Discovery returns the workspace default first, so the default follows the
75
+ // response rather than a constant; that keeps it right across an id rename.
76
+ return {
77
+ models,
78
+ defaultModel: models[0]?.id || BASE_AGENT_ID,
79
+ fetchedAt: new Date().toISOString(),
80
+ source: "api",
81
+ };
82
+ }
83
+ function normalizeAgent(value) {
84
+ const raw = asRecord(value);
85
+ const id = String(raw?.id || "").trim();
86
+ if (!raw || !id)
87
+ return null;
88
+ return {
89
+ id,
90
+ base_model: trimmedString(raw.base_model),
91
+ profile_id: trimmedString(raw.profile_id) ??
92
+ (raw.profile_id === null ? null : undefined),
93
+ source: trimmedString(raw.source),
94
+ enabled: typeof raw.enabled === "boolean" ? raw.enabled : undefined,
95
+ bucket_ids: uniqueStrings(raw.bucket_ids),
96
+ buckets: normalizeBuckets(raw.buckets),
97
+ missing_bucket_ids: uniqueStrings(raw.missing_bucket_ids),
98
+ };
99
+ }
100
+ function normalizeBuckets(value) {
101
+ return (Array.isArray(value) ? value : [])
102
+ .map(normalizeBucket)
103
+ .filter((bucket) => bucket !== null);
104
+ }
105
+ function normalizeBucket(value) {
106
+ const raw = asRecord(value);
107
+ const id = String(raw?.id || "").trim();
108
+ if (!raw || !id)
109
+ return null;
110
+ return {
111
+ id,
112
+ name: trimmedString(raw.name),
113
+ slug: trimmedString(raw.slug),
114
+ status: trimmedString(raw.status),
115
+ member_count: numberOrUndefined(raw.member_count),
116
+ };
117
+ }
@@ -0,0 +1,94 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import OpenAI from "openai";
3
+ import { requireApiKey } from "./CalypsoApiConfig.js";
4
+ /**
5
+ * Asks a Calypso agent through the OpenAI-compatible `POST /responses`.
6
+ *
7
+ * Each question is its own conversation. The server is stateless (every HTTP
8
+ * request builds a fresh one), so there is nowhere to keep a thread between
9
+ * calls and a follow-up must carry its own context in the prompt.
10
+ */
11
+ export class AgentResponses {
12
+ config;
13
+ userAgent;
14
+ client = null;
15
+ constructor(config, userAgent) {
16
+ this.config = config;
17
+ this.userAgent = userAgent;
18
+ }
19
+ static newConversationId() {
20
+ return `conv_${randomUUID().replace(/-/g, "")}`;
21
+ }
22
+ async ask(question) {
23
+ const stream = await this.openai().responses.create(AgentResponses.requestFor(question));
24
+ return AgentResponses.collect(stream);
25
+ }
26
+ // Built on first use: the SDK refuses to construct without a key, and that
27
+ // failure belongs in the tool result of the call that needed it.
28
+ openai() {
29
+ this.client ??= new OpenAI({
30
+ apiKey: requireApiKey(this.config),
31
+ baseURL: this.config.apiBaseUrl,
32
+ defaultHeaders: { "User-Agent": this.userAgent },
33
+ // The platform fetch, looked up per call, like every other Calypso
34
+ // request here: one transport to configure, trace and stub.
35
+ fetch: (url, init) => globalThis.fetch(url, init),
36
+ });
37
+ return this.client;
38
+ }
39
+ static requestFor(question) {
40
+ const fileIds = question.fileIds ?? [];
41
+ return {
42
+ model: question.agentId,
43
+ input: [
44
+ {
45
+ role: "user",
46
+ content: [
47
+ { type: "input_text", text: question.prompt },
48
+ ...fileIds.map((fileId) => ({
49
+ type: "input_file",
50
+ file_id: fileId,
51
+ })),
52
+ ],
53
+ },
54
+ ],
55
+ stream: true,
56
+ store: true,
57
+ metadata: AgentResponses.metadataFor(question),
58
+ conversation: { id: question.conversationId },
59
+ };
60
+ }
61
+ static metadataFor(question) {
62
+ return {
63
+ tool: "mcp",
64
+ agent: question.agentId,
65
+ conversation_id: question.conversationId,
66
+ // Named files are retrieved from, not pasted into the prompt whole.
67
+ ...(question.fileIds?.length
68
+ ? { _aicore: { file_input_strategy: "rag_policy" } }
69
+ : {}),
70
+ };
71
+ }
72
+ /** Folds the event stream into the answer text and the response id. */
73
+ static async collect(stream) {
74
+ let text = "";
75
+ let responseId = null;
76
+ for await (const event of stream) {
77
+ if (event.type === "response.output_text.delta" &&
78
+ typeof event.delta === "string") {
79
+ text += event.delta;
80
+ }
81
+ // Some responses skip deltas and only send the finished text.
82
+ if (event.type === "response.output_text.done" &&
83
+ !text &&
84
+ typeof event.text === "string") {
85
+ text = event.text;
86
+ }
87
+ if (event.type === "response.completed" &&
88
+ typeof event.response?.id === "string") {
89
+ responseId = event.response.id;
90
+ }
91
+ }
92
+ return { text, responseId };
93
+ }
94
+ }