@calypsohq/elephant-mcp-server 1.1.0 → 1.1.1

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
@@ -1,6 +1,15 @@
1
- # Elephant MCP server
1
+ # Elephant MCP server: PDF AI & docs Q&A for Claude, ChatGPT and Cursor
2
2
 
3
- The MCP server for Elephant by Calypso, in two shapes from one codebase:
3
+ Chat with your PDFs, documents and web pages from any MCP client, and get every answer with the file and page it came from. Save a file once at [elephant.calypso.so](https://elephant.calypso.so), then ask it from Claude, Claude Code, ChatGPT, Cursor or Windsurf.
4
+
5
+ - **Ask** your lecture notes, research papers, contracts, manuals, invoices and reports a question, and get an answer that cites its source.
6
+ - **Search** for the exact passage, returned in full with its file and page.
7
+ - **Save** PDFs, file links and web pages into buckets (folders) without leaving the chat.
8
+ - **No guessing**: when your sources do not cover a question, Elephant says so.
9
+
10
+ It is retrieval-augmented generation (RAG) over your own documents with nothing to run: no vector database, no embeddings to manage. See the [full readme](https://github.com/calypso-so/elephant-mcp#readme) for use cases and the hosted, no-key install.
11
+
12
+ One codebase, two shapes:
4
13
 
5
14
  - **Hosted**: stateless, one process serves both plugins over Streamable HTTP with OAuth (`dist/index.js`, deployed at `mcp.calypso.so`).
6
15
  - **Local**: `elephant-mcp` on stdio for one API key, published to npm as `@calypsohq/elephant-mcp-server` (`dist/stdio.js`).
@@ -49,6 +58,7 @@ An unauthenticated request gets `401` with `WWW-Authenticate: Bearer resource_me
49
58
  | `ELEPHANT_TOKEN_ENC_KEY` | — | 32-byte base64 key shared with the authorization server; unset turns OAuth off (API keys only) |
50
59
  | `CALYPSO_API_BASE_URL` | `https://api.calypso.so/v1` | Calypso API |
51
60
  | `ELEPHANT_REQUESTS_PER_MINUTE` | `120` | per-caller request budget |
61
+ | `ELEPHANT_OPENAI_CHALLENGE_TOKEN` | — | OpenAI plugin portal domain-verification token, served as plain text at `/.well-known/openai-apps-challenge`; unset answers 404 |
52
62
 
53
63
  ## Layout
54
64
 
@@ -44,6 +44,17 @@ export class AuthChallenge {
44
44
  params.push(`scope="${this.scope}"`);
45
45
  return `Bearer ${params.join(", ")}`;
46
46
  }
47
+ /**
48
+ * Why the request was refused, for the request log. Carries the error class
49
+ * and its fixed description only, never anything from the token.
50
+ */
51
+ logReason() {
52
+ if (!this.error)
53
+ return "missing";
54
+ if (this.error === "insufficient_scope")
55
+ return "insufficient_scope";
56
+ return `${this.error}: ${this.description}`;
57
+ }
47
58
  body() {
48
59
  return {
49
60
  error: this.error ?? "unauthorized",
@@ -1,5 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import OpenAI from "openai";
3
+ import { AnswerDepth } from "./AnswerDepth.js";
4
+ import { AnswerSources } from "./AnswerSources.js";
3
5
  import { requireApiKey } from "./CalypsoApiConfig.js";
4
6
  /**
5
7
  * Asks a Calypso agent through the OpenAI-compatible `POST /responses`.
@@ -63,16 +65,21 @@ export class AgentResponses {
63
65
  tool: "mcp",
64
66
  agent: question.agentId,
65
67
  conversation_id: question.conversationId,
68
+ ...(question.depth
69
+ ? { response_policy: question.depth.responsePolicy }
70
+ : {}),
66
71
  // Named files are retrieved from, not pasted into the prompt whole.
67
72
  ...(question.fileIds?.length
68
73
  ? { _aicore: { file_input_strategy: "rag_policy" } }
69
74
  : {}),
70
75
  };
71
76
  }
72
- /** Folds the event stream into the answer text and the response id. */
77
+ /** Folds the event stream into the answer text, its sources and the response id. */
73
78
  static async collect(stream) {
74
79
  let text = "";
75
80
  let responseId = null;
81
+ let sources = AnswerSources.none();
82
+ let depth;
76
83
  for await (const event of stream) {
77
84
  if (event.type === "response.output_text.delta" &&
78
85
  typeof event.delta === "string") {
@@ -84,11 +91,14 @@ export class AgentResponses {
84
91
  typeof event.text === "string") {
85
92
  text = event.text;
86
93
  }
87
- if (event.type === "response.completed" &&
88
- typeof event.response?.id === "string") {
89
- responseId = event.response.id;
94
+ if (event.type === "response.completed") {
95
+ if (typeof event.response?.id === "string") {
96
+ responseId = event.response.id;
97
+ }
98
+ sources = AnswerSources.fromResponse(event.response);
99
+ depth = AnswerDepth.used(event.response);
90
100
  }
91
101
  }
92
- return { text, responseId };
102
+ return { text, responseId, sources, depth };
93
103
  }
94
104
  }
@@ -0,0 +1,57 @@
1
+ /** The depths a caller may ask for, shallowest first. */
2
+ export const ANSWER_DEPTHS = ["fast", "balanced", "deep"];
3
+ /** The depths a search may run at. */
4
+ export const SEARCH_DEPTHS = ["fast", "thorough"];
5
+ /**
6
+ * How much work an answer is worth: which Calypso response tier writes it.
7
+ *
8
+ * Callers pick a depth in plain words; the Calypso API speaks in response
9
+ * policies (`fast`, `medium`, `extended`) and reports the tier it actually
10
+ * used as an OpenAI reasoning effort. This class is the only place that knows
11
+ * both vocabularies, so a tool never has to.
12
+ */
13
+ export class AnswerDepth {
14
+ name;
15
+ responsePolicy;
16
+ efforts;
17
+ static ALL = [
18
+ new AnswerDepth("fast", "fast", ["minimal", "low"]),
19
+ new AnswerDepth("balanced", "medium", ["medium"]),
20
+ new AnswerDepth("deep", "extended", ["high"]),
21
+ ];
22
+ constructor(name,
23
+ /** The `response_policy` the Calypso API takes. */
24
+ responsePolicy, efforts) {
25
+ this.name = name;
26
+ this.responsePolicy = responsePolicy;
27
+ this.efforts = efforts;
28
+ }
29
+ /** The depth a caller named; undefined when none was asked for. */
30
+ static named(name) {
31
+ const wanted = String(name ?? "")
32
+ .trim()
33
+ .toLowerCase();
34
+ return AnswerDepth.ALL.find((depth) => depth.name === wanted);
35
+ }
36
+ /** The depth a finished response says it ran at, from its reasoning effort. */
37
+ static used(response) {
38
+ const reasoning = response !== null && typeof response === "object"
39
+ ? response.reasoning
40
+ : undefined;
41
+ const effort = String(reasoning?.effort ?? "")
42
+ .trim()
43
+ .toLowerCase();
44
+ return AnswerDepth.ALL.find((depth) => depth.efforts.includes(effort));
45
+ }
46
+ /** Whether this depth does less work than the other. */
47
+ isShallowerThan(other) {
48
+ return AnswerDepth.ALL.indexOf(this) < AnswerDepth.ALL.indexOf(other);
49
+ }
50
+ }
51
+ /** The search depth the Calypso API takes for a caller's word. */
52
+ export function searchDepthForApi(depth, extraQueries) {
53
+ // Extra phrasings only run at the deeper setting, so naming any asks for it.
54
+ if (depth === "thorough" || extraQueries > 0)
55
+ return "standard";
56
+ return depth === "fast" ? "fast" : undefined;
57
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * The sources a completed agent response says it used.
3
+ *
4
+ * The Calypso API streams the answer as text and reports its sources on the
5
+ * finished response, not inside the text: in `metadata._aicore.grounded_sources`
6
+ * and as `annotations` on the output text. A reader of the text alone sees an
7
+ * answer with no source, so they are read here and written out under it.
8
+ */
9
+ export class AnswerSources {
10
+ items;
11
+ constructor(items) {
12
+ this.items = items;
13
+ }
14
+ /** No sources: an answer that names none, or one not finished yet. */
15
+ static none() {
16
+ return new AnswerSources([]);
17
+ }
18
+ /** Sources of a `response.completed` payload; empty when it names none. */
19
+ static fromResponse(response) {
20
+ const grounded = AnswerSources.fromGroundedSources(response);
21
+ const found = grounded.length
22
+ ? grounded
23
+ : AnswerSources.fromAnnotations(response);
24
+ return new AnswerSources(AnswerSources.distinct(found));
25
+ }
26
+ get count() {
27
+ return this.items.length;
28
+ }
29
+ /** The block appended under an answer; empty when there are no sources. */
30
+ render() {
31
+ if (!this.items.length)
32
+ return "";
33
+ const lines = this.items.map((source, index) => {
34
+ const details = [
35
+ source.locator,
36
+ source.fileId ? `file id ${source.fileId}` : undefined,
37
+ source.url && source.url !== source.label ? source.url : undefined,
38
+ ].filter(Boolean);
39
+ const suffix = details.length ? ` (${details.join(", ")})` : "";
40
+ return `${index + 1}. ${source.label}${suffix}`;
41
+ });
42
+ return `Sources:\n${lines.join("\n")}`;
43
+ }
44
+ static fromGroundedSources(response) {
45
+ const metadata = AnswerSources.object(AnswerSources.object(response).metadata);
46
+ const items = AnswerSources.object(metadata._aicore).grounded_sources;
47
+ return AnswerSources.list(items).flatMap((item) => {
48
+ const url = AnswerSources.text(item.url);
49
+ const label = AnswerSources.text(item.filename) ??
50
+ AnswerSources.text(item.title) ??
51
+ AnswerSources.text(item.label) ??
52
+ url;
53
+ if (!label)
54
+ return [];
55
+ const page = item.page_number;
56
+ const locator = AnswerSources.text(item.page_label) ??
57
+ AnswerSources.text(item.locator_label) ??
58
+ (typeof page === "number" ? `p. ${page}` : undefined);
59
+ return [
60
+ {
61
+ label,
62
+ fileId: AnswerSources.text(item.knowledge_id),
63
+ url,
64
+ locator,
65
+ },
66
+ ];
67
+ });
68
+ }
69
+ static fromAnnotations(response) {
70
+ const output = AnswerSources.list(AnswerSources.object(response).output);
71
+ const annotations = output
72
+ .flatMap((item) => AnswerSources.list(item.content))
73
+ .flatMap((part) => AnswerSources.list(part.annotations));
74
+ return annotations.flatMap((annotation) => {
75
+ const url = AnswerSources.text(annotation.url);
76
+ const label = AnswerSources.text(annotation.filename) ??
77
+ AnswerSources.text(annotation.title) ??
78
+ url;
79
+ if (!label)
80
+ return [];
81
+ return [{ label, fileId: AnswerSources.text(annotation.file_id), url }];
82
+ });
83
+ }
84
+ /** One line per source and place: a file cited five times is listed once. */
85
+ static distinct(sources) {
86
+ const seen = new Set();
87
+ return sources.filter((source) => {
88
+ const key = [
89
+ source.fileId ?? source.url ?? source.label,
90
+ source.locator ?? "",
91
+ ].join("|");
92
+ if (seen.has(key))
93
+ return false;
94
+ seen.add(key);
95
+ return true;
96
+ });
97
+ }
98
+ static object(value) {
99
+ return value !== null && typeof value === "object" && !Array.isArray(value)
100
+ ? value
101
+ : {};
102
+ }
103
+ static list(value) {
104
+ return Array.isArray(value) ? value.map(AnswerSources.object) : [];
105
+ }
106
+ static text(value) {
107
+ const text = typeof value === "string" ? value.trim() : "";
108
+ return text || undefined;
109
+ }
110
+ }
@@ -1,4 +1,7 @@
1
+ import { searchDepthForApi } from "./AnswerDepth.js";
1
2
  const MAX_RESULTS = 20;
3
+ /** The API searches at most this many extra phrasings. */
4
+ export const MAX_EXTRA_QUERIES = 2;
2
5
  /**
3
6
  * Retrieval without an answer (`POST /search`): the passages and sources an
4
7
  * agent would cite, for callers that want the evidence itself.
@@ -13,6 +16,11 @@ export class KnowledgeSearch {
13
16
  const buckets = (options.buckets ?? [])
14
17
  .map((item) => String(item || "").trim())
15
18
  .filter(Boolean);
19
+ const extra = (options.alsoSearchFor ?? [])
20
+ .map((item) => String(item || "").trim())
21
+ .filter(Boolean)
22
+ .slice(0, MAX_EXTRA_QUERIES);
23
+ const depth = searchDepthForApi(options.depth, extra.length);
16
24
  return this.api.request("/search", {
17
25
  method: "POST",
18
26
  body: {
@@ -20,6 +28,8 @@ export class KnowledgeSearch {
20
28
  ...(agent ? { agent } : {}),
21
29
  ...(options.buckets?.length ? { buckets } : {}),
22
30
  ...maxResultsField(options.maxResults),
31
+ ...(depth ? { depth } : {}),
32
+ ...(extra.length ? { additional_queries: extra } : {}),
23
33
  },
24
34
  });
25
35
  }
@@ -45,6 +45,7 @@ export function composeHostedServer(config, packageInfo) {
45
45
  metadata,
46
46
  maxBodyBytes: config.maxBodyBytes,
47
47
  version: packageInfo.version,
48
+ openaiChallengeToken: config.openaiChallengeToken,
48
49
  log: (line) => console.log(JSON.stringify(line)),
49
50
  });
50
51
  }
@@ -16,6 +16,7 @@ const DEFAULT_REQUESTS_PER_MINUTE = 120;
16
16
  * | ELEPHANT_TOKEN_ENC_KEY | 32-byte base64 key for the `ek` claim; unset = OAuth off, API keys only |
17
17
  * | CALYPSO_API_BASE_URL | Calypso API base URL (…/v1) |
18
18
  * | ELEPHANT_REQUESTS_PER_MINUTE | per-caller request budget (default 120) |
19
+ * | ELEPHANT_OPENAI_CHALLENGE_TOKEN | OpenAI plugin portal domain-verification token (public) |
19
20
  */
20
21
  export class HttpConfig {
21
22
  port;
@@ -26,7 +27,8 @@ export class HttpConfig {
26
27
  apiBaseUrl;
27
28
  maxBodyBytes;
28
29
  requestsPerMinute;
29
- constructor(port, publicBaseUrl, issuer, jwksUrl, tokenEncKey, apiBaseUrl, maxBodyBytes, requestsPerMinute) {
30
+ openaiChallengeToken;
31
+ constructor(port, publicBaseUrl, issuer, jwksUrl, tokenEncKey, apiBaseUrl, maxBodyBytes, requestsPerMinute, openaiChallengeToken) {
30
32
  this.port = port;
31
33
  this.publicBaseUrl = publicBaseUrl;
32
34
  this.issuer = issuer;
@@ -35,6 +37,7 @@ export class HttpConfig {
35
37
  this.apiBaseUrl = apiBaseUrl;
36
38
  this.maxBodyBytes = maxBodyBytes;
37
39
  this.requestsPerMinute = requestsPerMinute;
40
+ this.openaiChallengeToken = openaiChallengeToken;
38
41
  }
39
42
  static fromEnv(env) {
40
43
  const issuer = stripSlash(env.CALYPSO_OAUTH_ISSUER) ?? DEFAULT_OAUTH_ISSUER;
@@ -42,7 +45,7 @@ export class HttpConfig {
42
45
  if (!apiBaseUrl.endsWith("/v1")) {
43
46
  throw new Error("CALYPSO_API_BASE_URL must end in /v1.");
44
47
  }
45
- 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"));
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);
46
49
  }
47
50
  get oauthEnabled() {
48
51
  return Boolean(this.tokenEncKey);
@@ -6,6 +6,7 @@ const CORS_HEADERS = {
6
6
  "Access-Control-Allow-Headers": "Authorization, Content-Type, Mcp-Protocol-Version, Mcp-Session-Id",
7
7
  "Access-Control-Expose-Headers": "WWW-Authenticate, Mcp-Session-Id",
8
8
  };
9
+ export const OPENAI_CHALLENGE_PATH = "/.well-known/openai-apps-challenge";
9
10
  class HttpError extends Error {
10
11
  status;
11
12
  constructor(status, message) {
@@ -42,9 +43,9 @@ export class HttpServer {
42
43
  async route(req, res) {
43
44
  const started = Date.now();
44
45
  const path = new URL(req.url ?? "/", "http://localhost").pathname.replace(/\/+$/, "") || "/";
45
- let principal;
46
+ let outcome;
46
47
  try {
47
- principal = await this.dispatch(path, req, res);
48
+ outcome = await this.dispatch(path, req, res);
48
49
  }
49
50
  catch (error) {
50
51
  this.fail(res, error);
@@ -54,7 +55,10 @@ export class HttpServer {
54
55
  method: req.method,
55
56
  path,
56
57
  status: res.statusCode,
57
- principal,
58
+ principal: outcome?.principal,
59
+ // Set on a 401/403 only: without it a refusal for a missing token and
60
+ // one for a rejected token are the same log line.
61
+ auth: outcome?.refused,
58
62
  ms: Date.now() - started,
59
63
  ua: req.headers["user-agent"],
60
64
  });
@@ -67,6 +71,14 @@ export class HttpServer {
67
71
  if (path === "/healthz" && req.method === "GET") {
68
72
  return this.json(res, 200, { ok: true, version: this.options.version });
69
73
  }
74
+ if (path === OPENAI_CHALLENGE_PATH && this.options.openaiChallengeToken) {
75
+ if (req.method !== "GET")
76
+ throw new HttpError(405, "Method not allowed.");
77
+ // Exactly the token: the portal rejects JSON or anything around it.
78
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
79
+ res.end(this.options.openaiChallengeToken);
80
+ return undefined;
81
+ }
70
82
  const described = this.metadataByPath.get(path);
71
83
  if (described) {
72
84
  if (req.method !== "GET")
@@ -15,20 +15,20 @@ export class McpEndpoint {
15
15
  this.options = options;
16
16
  this.preset = options.preset;
17
17
  }
18
- /** Returns the principal handled, or undefined when refused. */
18
+ /** Who was served, or why the request was refused. */
19
19
  async handle(req, res, body) {
20
20
  const result = await this.options.authenticator.authenticate(req.headers.authorization, this.preset);
21
21
  if (result instanceof AuthChallenge) {
22
22
  McpEndpoint.refuse(res, result);
23
- return undefined;
23
+ return { refused: result.logReason() };
24
24
  }
25
25
  const decision = this.options.limiter.take(result.principal);
26
26
  if (!decision.allowed) {
27
27
  McpEndpoint.throttle(res, decision.retryAfterSeconds);
28
- return result.principal;
28
+ return { principal: result.principal };
29
29
  }
30
30
  await this.serve(req, res, body, result);
31
- return result.principal;
31
+ return { principal: result.principal };
32
32
  }
33
33
  async serve(req, res, body, credential) {
34
34
  const api = {
@@ -16,6 +16,7 @@ const elephant = new ToolPreset({
16
16
  scope: "elephant:read",
17
17
  instructions: [
18
18
  "Elephant by Calypso answers from this team's Calypso knowledge — the documents, websites and images the team has added — and cites every source.",
19
+ "Answers and searches have a depth. Start shallow and go one step deeper only when a result is thin or says the knowledge does not cover something the user expects: `depth` on elephant-ask (`fast`, `balanced`, `deep`) and on elephant-search (`fast`, `thorough`, with `alsoSearchFor`).",
19
20
  "It is read-only: it cannot add, change or delete knowledge. To add files or websites, use Elephant Builder by Calypso.",
20
21
  "When the knowledge does not cover a question, say so instead of answering from general knowledge.",
21
22
  ].join(" "),
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { AgentResponses } from "../calypso/AgentResponses.js";
3
+ import { ANSWER_DEPTHS, AnswerDepth } from "../calypso/AnswerDepth.js";
3
4
  import { compactStrings } from "../calypso/coerce.js";
4
5
  import { emptyKnowledgeAnswer } from "../hatching/HatchingCopy.js";
5
6
  import { ElephantTool, } from "./ElephantTool.js";
@@ -16,6 +17,16 @@ const inputSchema = {
16
17
  .string()
17
18
  .optional()
18
19
  .describe("Optional id of one of the team's Calypso agents. Omit to use the team's default agent."),
20
+ depth: z
21
+ .enum(ANSWER_DEPTHS)
22
+ .optional()
23
+ .describe([
24
+ "How much work the answer is worth. Omit it for the agent's own default.",
25
+ "`fast`: a lookup of one stated fact (a price, a date, a limit); a few seconds.",
26
+ "`balanced`: an explanation or summary that draws on a few passages; around 20 seconds.",
27
+ "`deep`: comparing or reconciling several sources, or an answer someone will act on; the slowest.",
28
+ "Start at the lowest depth that fits the question and raise it only on a retry.",
29
+ ].join(" ")),
19
30
  };
20
31
  /** `elephant-ask`: a cited answer written from the team's knowledge. */
21
32
  export class AskTool extends ElephantTool {
@@ -28,10 +39,17 @@ export class AskTool extends ElephantTool {
28
39
  "Always cite the sources the answer returns. If the answer says the knowledge does not cover the question, say so plainly instead of answering from general knowledge.",
29
40
  "Each call stands alone: put everything needed to answer, including the subject of a follow-up, in the prompt.",
30
41
  "Optional `model` picks one of the team's Calypso agents; omit it to use the default.",
42
+ "Optional `depth` (`fast`, `balanced`, `deep`) sets how much work the answer gets. Choose it from the question, not from habit: `fast` for one stated fact, `balanced` for an explanation or summary, `deep` when several sources must be compared or the answer will be acted on. The reply ends by naming the depth it was answered at.",
43
+ "If an answer is thin, misses part of the question, or says the knowledge does not cover something the user expects to be there, ask once more one depth higher before telling the user it is not covered. Do not repeat a call at the same depth, and do not go above `deep`.",
44
+ "A team's plan may cap depth; when the reply says it was answered at a lower depth than asked, that is the most this team allows, so do not retry higher.",
31
45
  "When the team has no knowledge yet, the answer says so and how to add a first source; relay it, do not answer from general knowledge.",
32
46
  ].join("\n");
33
47
  inputSchema = inputSchema;
34
- annotations = { readOnlyHint: true, openWorldHint: true };
48
+ annotations = {
49
+ readOnlyHint: true,
50
+ destructiveHint: false,
51
+ openWorldHint: false,
52
+ };
35
53
  failure = "Elephant could not answer.";
36
54
  async run(args, { api, agents, inventory, log }) {
37
55
  // An empty team gets the hatch, never an apology from an agent with
@@ -44,6 +62,7 @@ export class AskTool extends ElephantTool {
44
62
  return { text: emptyKnowledgeAnswer() };
45
63
  }
46
64
  const agentId = agents.resolve(args.model);
65
+ const asked = AnswerDepth.named(args.depth);
47
66
  const fileIds = compactStrings(args.fileIds);
48
67
  const conversationId = AgentResponses.newConversationId();
49
68
  await log.event("info", "Asking a Calypso agent.", {
@@ -57,13 +76,43 @@ export class AskTool extends ElephantTool {
57
76
  prompt: args.prompt.trim(),
58
77
  fileIds,
59
78
  conversationId,
79
+ depth: asked,
60
80
  });
61
81
  await log.event("info", "Calypso agent answered.", {
62
82
  tool: this.name,
63
83
  agent: agentId,
64
84
  responseId: answer.responseId,
65
85
  textLength: answer.text.length,
86
+ sourceCount: answer.sources.count,
87
+ depthAsked: asked?.name,
88
+ depthUsed: answer.depth?.name,
66
89
  });
67
- return { text: answer.text };
90
+ // The API reports sources beside the text, not in it. Without this block
91
+ // a correct, grounded answer reaches the client looking uncited.
92
+ const sources = AskTool.namesItsSources(answer.text)
93
+ ? ""
94
+ : answer.sources.render();
95
+ const parts = [
96
+ answer.text,
97
+ sources,
98
+ AskTool.depthNote(asked, answer.depth),
99
+ ];
100
+ return { text: parts.filter(Boolean).join("\n\n") };
101
+ }
102
+ /**
103
+ * One closing line saying the depth the answer got, so the caller knows
104
+ * what a retry one step higher would buy, and when a plan capped the ask.
105
+ */
106
+ static depthNote(asked, used) {
107
+ if (!used)
108
+ return "";
109
+ if (asked && used.isShallowerThan(asked)) {
110
+ return `Answered at depth: ${used.name} (asked for ${asked.name}; this team's plan caps depth here, so a higher depth will not change the answer).`;
111
+ }
112
+ return `Answered at depth: ${used.name}.`;
113
+ }
114
+ /** Whether the answer text already ends in its own list of sources. */
115
+ static namesItsSources(text) {
116
+ return /(^|\n)\s*(\*\*)?(sources|references|fuentes|referencias)(\*\*)?:\s*\n/i.test(text);
68
117
  }
69
118
  }
@@ -18,8 +18,9 @@ export class ListBucketsTool extends ElephantTool {
18
18
  inputSchema = inputSchema;
19
19
  annotations = {
20
20
  readOnlyHint: true,
21
+ destructiveHint: false,
21
22
  idempotentHint: true,
22
- openWorldHint: true,
23
+ openWorldHint: false,
23
24
  };
24
25
  failure = "Listing the team's buckets failed.";
25
26
  async run(args, { api, log }) {
@@ -22,8 +22,9 @@ export class OpenSourceTool extends ElephantTool {
22
22
  inputSchema = inputSchema;
23
23
  annotations = {
24
24
  readOnlyHint: true,
25
+ destructiveHint: false,
25
26
  idempotentHint: true,
26
- openWorldHint: true,
27
+ openWorldHint: false,
27
28
  };
28
29
  failure = "Opening the source failed.";
29
30
  async run(args, { api }) {
@@ -1,4 +1,6 @@
1
1
  import { z } from "zod";
2
+ import { SEARCH_DEPTHS } from "../calypso/AnswerDepth.js";
3
+ import { MAX_EXTRA_QUERIES } from "../calypso/KnowledgeSearch.js";
2
4
  import { emptyKnowledgeAnswer } from "../hatching/HatchingCopy.js";
3
5
  import { ElephantTool, } from "./ElephantTool.js";
4
6
  const inputSchema = {
@@ -18,7 +20,16 @@ const inputSchema = {
18
20
  .min(1)
19
21
  .max(20)
20
22
  .optional()
21
- .describe("How many passages to return, 1 to 20 (default 10)."),
23
+ .describe("The most passages to return, 1 to 20 (default 10). A ceiling, not a target: a search returns as many passages as it finds."),
24
+ depth: z
25
+ .enum(SEARCH_DEPTHS)
26
+ .optional()
27
+ .describe("`fast` (default) runs one search. `thorough` runs several in parallel and merges them: use it when a fast search came back with fewer passages than the question deserves, or when you are gathering evidence, not checking one fact."),
28
+ alsoSearchFor: z
29
+ .array(z.string().min(1))
30
+ .max(MAX_EXTRA_QUERIES)
31
+ .optional()
32
+ .describe(`Up to ${MAX_EXTRA_QUERIES} other ways of saying the same thing, searched alongside \`query\` (this makes the search thorough). Write them as the document would: its own terms, a synonym, the specific item ("express delivery times", "international shipping days"). This is the strongest way to get more of a document back.`),
22
33
  };
23
34
  /** `elephant-search`: matching passages and their sources, no answer. */
24
35
  export class SearchTool extends ElephantTool {
@@ -28,13 +39,16 @@ export class SearchTool extends ElephantTool {
28
39
  "Searches the team's Calypso knowledge and returns the matching passages and their sources, without writing an answer.",
29
40
  "",
30
41
  "Use it when the user wants the exact wording, quotes, or a list of where something is mentioned.",
42
+ "Each result's `text` is one whole matching passage as the document has it, and `quote`, when present, is the line in that passage that matched most closely. Read the whole `text` before searching again: a short document is one passage, so a single result can hold everything it says on the subject.",
43
+ 'Quote wording to the user from `text`, never from memory. When the passages returned do not cover what the user expects, search again with `depth: "thorough"` and `alsoSearchFor` (other phrasings, or the specific items you expect), or narrow to `buckets`. To have the content read and summarised, use elephant-ask instead.',
31
44
  "Pass `buckets` (ids or slugs from elephant-list-buckets, up to 5) to search specific buckets, or `agent` to search what one Calypso agent can see — not both.",
32
45
  ].join("\n");
33
46
  inputSchema = inputSchema;
34
47
  annotations = {
35
48
  readOnlyHint: true,
49
+ destructiveHint: false,
36
50
  idempotentHint: true,
37
- openWorldHint: true,
51
+ openWorldHint: false,
38
52
  };
39
53
  failure = "Searching Elephant failed.";
40
54
  async run(args, { api, inventory, log }) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@calypsohq/elephant-mcp-server",
3
- "version": "1.1.0",
4
- "description": "Elephant by Calypso: MCP server for your team's Calypso knowledge. Hosted (Streamable HTTP, OAuth) or local over stdio with an API key.",
3
+ "version": "1.1.1",
4
+ "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.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": {
@@ -17,9 +17,18 @@
17
17
  "model-context-protocol",
18
18
  "elephant",
19
19
  "calypso",
20
+ "mcp-server",
21
+ "pdf",
22
+ "pdf-ai",
23
+ "chat-with-pdf",
24
+ "document-qa",
20
25
  "rag",
21
- "knowledge",
26
+ "retrieval-augmented-generation",
27
+ "citations",
28
+ "knowledge-base",
29
+ "second-brain",
22
30
  "claude",
31
+ "claude-code",
23
32
  "chatgpt",
24
33
  "cursor"
25
34
  ],