@caplets/core 0.18.6 → 0.18.8

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.
@@ -49,11 +49,11 @@ export declare function generatedToolInputSchemaForCaplet(caplet: CapletSchemaBa
49
49
  arguments: z.ZodOptional<z.ZodObject<{}, z.core.$catchall<z.ZodAny>>>;
50
50
  fields: z.ZodOptional<z.ZodArray<z.ZodString>>;
51
51
  operation: z.ZodEnum<{
52
- get_caplet: "get_caplet";
53
- check_backend: "check_backend";
54
52
  list_tools: "list_tools";
55
53
  search_tools: "search_tools";
56
54
  get_tool: "get_tool";
55
+ check_backend: "check_backend";
56
+ get_caplet: "get_caplet";
57
57
  call_tool: "call_tool";
58
58
  }>;
59
59
  }, z.core.$strict>;
@@ -64,11 +64,11 @@ export declare const generatedToolInputSchema: z.ZodObject<{
64
64
  arguments: z.ZodOptional<z.ZodObject<{}, z.core.$catchall<z.ZodAny>>>;
65
65
  fields: z.ZodOptional<z.ZodArray<z.ZodString>>;
66
66
  operation: z.ZodEnum<{
67
- get_caplet: "get_caplet";
68
- check_backend: "check_backend";
69
67
  list_tools: "list_tools";
70
68
  search_tools: "search_tools";
71
69
  get_tool: "get_tool";
70
+ check_backend: "check_backend";
71
+ get_caplet: "get_caplet";
72
72
  call_tool: "call_tool";
73
73
  }>;
74
74
  }, z.core.$strict>;
@@ -1,2 +1,2 @@
1
- import { a as generatedToolInputJsonSchemaForCaplet, c as mcpOperations, i as generatedToolInputJsonSchema, l as operations, n as completionRefSchema, o as generatedToolInputSchema, r as generatedToolInputDescriptions, s as generatedToolInputSchemaForCaplet, t as completionArgumentSchema } from "./generated-tool-input-schema-BYoyY-l-.js";
1
+ import { a as generatedToolInputJsonSchemaForCaplet, c as mcpOperations, i as generatedToolInputJsonSchema, l as operations, n as completionRefSchema, o as generatedToolInputSchema, r as generatedToolInputDescriptions, s as generatedToolInputSchemaForCaplet, t as completionArgumentSchema } from "./generated-tool-input-schema-MbYF5jMW.js";
2
2
  export { completionArgumentSchema, completionRefSchema, generatedToolInputDescriptions, generatedToolInputJsonSchema, generatedToolInputJsonSchemaForCaplet, generatedToolInputSchema, generatedToolInputSchemaForCaplet, mcpOperations, operations };
package/dist/graphql.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CompatibilityCallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
1
+ import type { CompatibilityCallToolResult, Tool } from "@modelcontextprotocol/sdk/types";
2
2
  import type { GraphQlEndpointConfig } from "./config";
3
3
  import type { CompactTool } from "./downstream";
4
4
  import type { ServerRegistry } from "./registry";
@@ -1,4 +1,4 @@
1
- import type { CompatibilityCallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
1
+ import type { CompatibilityCallToolResult, Tool } from "@modelcontextprotocol/sdk/types";
2
2
  import type { HttpApiConfig } from "./config";
3
3
  import type { CompactTool } from "./downstream";
4
4
  import type { ServerRegistry } from "./registry";
package/dist/index.d.ts CHANGED
@@ -3,5 +3,7 @@ export { runCli, createProgram } from "./cli";
3
3
  export { parseConfig, loadConfig } from "./config";
4
4
  export { capabilityDescription, ServerRegistry } from "./registry";
5
5
  export { generatedToolInputSchema, handleServerTool } from "./tools";
6
+ export { hasRenderableStructuredContent, markdownCallToolResultContent, markdownStructuredContent, } from "./result-content";
7
+ export type { ResultMarkdownContext } from "./result-content";
6
8
  export { serveCaplets, serveHttp, serveResolvedCaplets, serveStdio } from "./serve";
7
9
  export type { HttpServeOptions, RawServeOptions, ServeOptions, StdioServeOptions } from "./serve";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { $ as assertCompleteRequestPrompt, A as CreateMessageResultSchema, At as CAPLETS_ERROR_CODES, B as JSONRPCMessageSchema, C as AjvJsonSchemaValidator, Ct as resolveCapletsRoot, D as CallToolRequestSchema, Dt as discoverCapletFiles, E as toJsonSchemaCompat, Et as resolveProjectConfigPath, F as EmptyResultSchema, G as ListRootsResultSchema, H as ListPromptsRequestSchema, I as ErrorCode, It as __require, J as McpError, K as ListToolsRequestSchema, L as GetPromptRequestSchema, Lt as __toESM, M as CreateTaskResultSchema, Mt as redactSecrets, Nt as toSafeError, O as CallToolResultSchema, Ot as validateCapletFile, P as ElicitResultSchema, Pt as __commonJSMin, R as InitializeRequestSchema, S as assertToolsCallTaskCapability, T as mergeCapabilities, Tt as resolveProjectCapletsRoot, U as ListResourceTemplatesRequestSchema, V as LATEST_PROTOCOL_VERSION, W as ListResourcesRequestSchema, X as SUPPORTED_PROTOCOL_VERSIONS, Y as ReadResourceRequestSchema, Z as SetLevelRequestSchema, _t as loadGlobalConfig, a as resolveCapletsServer, at as getLiteralValue, bt as parseConfig, c as ServerRegistry, ct as getSchemaDescription, d as runOAuthFlow, dt as normalizeObjectSchema, et as assertCompleteRequestResourceTemplate, f as startGenericOAuthFlow, ft as objectFromShape, g as readTokenBundle, gt as loadConfigWithSources, h as isTokenBundleExpired, ht as loadConfig, i as resolveCapletsMode, it as isJSONRPCResultResponse, j as CreateMessageResultWithToolsSchema, jt as CapletsError, k as CompleteRequestSchema, kt as SERVER_ID_PATTERN, l as capabilityDescription, lt as isSchemaOptional, m as deleteTokenBundle, mt as safeParseAsync, nt as isJSONRPCErrorResponse, o as CapletsEngine, ot as getObjectShape, p as startOAuthFlow, pt as safeParse, q as LoggingLevelSchema, r as parseServerBaseUrl, rt as isJSONRPCRequest, s as handleServerTool, st as getParseErrorMessage, t as controlUrlForBase, tt as isInitializeRequest, u as runGenericOAuthFlow, ut as isZ4Schema, v as ReadBuffer, vt as loadLocalOverlayConfigWithSources, w as Protocol, wt as resolveConfigPath, x as assertClientRequestTaskCapability, y as serializeMessage, yt as loadProjectConfig, z as InitializedNotificationSchema } from "./options-BlNyqF_E.js";
2
- import { A as url, C as object, D as string, b as literal, d as ZodOptional, o as generatedToolInputSchema, s as generatedToolInputSchemaForCaplet } from "./generated-tool-input-schema-BYoyY-l-.js";
3
- import { a as formatCapletList, c as resolveCliConfigPaths, l as cliCommands, n as completionScript, o as formatConfigPaths, s as listCaplets, t as completeCliWords, u as completionShells } from "./completion-DRPTunQd.js";
1
+ import { $ as assertCompleteRequestPrompt, A as CreateMessageResultSchema, At as hasRenderableStructuredContent, B as JSONRPCMessageSchema, Bt as __toESM, C as AjvJsonSchemaValidator, Ct as resolveCapletsRoot, D as CallToolRequestSchema, Dt as discoverCapletFiles, E as toJsonSchemaCompat, Et as resolveProjectConfigPath, F as EmptyResultSchema, Ft as redactSecrets, G as ListRootsResultSchema, H as ListPromptsRequestSchema, I as ErrorCode, It as toSafeError, J as McpError, K as ListToolsRequestSchema, L as GetPromptRequestSchema, Lt as __commonJSMin, M as CreateTaskResultSchema, Mt as markdownStructuredContent, Nt as CAPLETS_ERROR_CODES, O as CallToolResultSchema, Ot as validateCapletFile, P as ElicitResultSchema, Pt as CapletsError, R as InitializeRequestSchema, S as assertToolsCallTaskCapability, T as mergeCapabilities, Tt as resolveProjectCapletsRoot, U as ListResourceTemplatesRequestSchema, V as LATEST_PROTOCOL_VERSION, W as ListResourcesRequestSchema, X as SUPPORTED_PROTOCOL_VERSIONS, Y as ReadResourceRequestSchema, Z as SetLevelRequestSchema, _t as loadGlobalConfig, a as resolveCapletsServer, at as getLiteralValue, bt as parseConfig, c as ServerRegistry, ct as getSchemaDescription, d as runOAuthFlow, dt as normalizeObjectSchema, et as assertCompleteRequestResourceTemplate, f as startGenericOAuthFlow, ft as objectFromShape, g as readTokenBundle, gt as loadConfigWithSources, h as isTokenBundleExpired, ht as loadConfig, i as resolveCapletsMode, it as isJSONRPCResultResponse, j as CreateMessageResultWithToolsSchema, jt as markdownCallToolResultContent, k as CompleteRequestSchema, kt as SERVER_ID_PATTERN, l as capabilityDescription, lt as isSchemaOptional, m as deleteTokenBundle, mt as safeParseAsync, nt as isJSONRPCErrorResponse, o as CapletsEngine, ot as getObjectShape, p as startOAuthFlow, pt as safeParse, q as LoggingLevelSchema, r as parseServerBaseUrl, rt as isJSONRPCRequest, s as handleServerTool, st as getParseErrorMessage, t as controlUrlForBase, tt as isInitializeRequest, u as runGenericOAuthFlow, ut as isZ4Schema, v as ReadBuffer, vt as loadLocalOverlayConfigWithSources, w as Protocol, wt as resolveConfigPath, x as assertClientRequestTaskCapability, y as serializeMessage, yt as loadProjectConfig, z as InitializedNotificationSchema, zt as __require } from "./options--RoZwWjs.js";
2
+ import { A as url, C as object, D as string, b as literal, d as ZodOptional, o as generatedToolInputSchema, s as generatedToolInputSchemaForCaplet } from "./generated-tool-input-schema-MbYF5jMW.js";
3
+ import { a as formatCapletList, c as resolveCliConfigPaths, l as cliCommands, n as completionScript, o as formatConfigPaths, s as listCaplets, t as completeCliWords, u as completionShells } from "./completion-DvWQk5qR.js";
4
4
  import { accessSync, chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
5
5
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
6
6
  import { execFileSync } from "node:child_process";
@@ -1320,7 +1320,7 @@ const EMPTY_COMPLETION_RESULT = { completion: {
1320
1320
  } };
1321
1321
  //#endregion
1322
1322
  //#region package.json
1323
- var version = "0.18.6";
1323
+ var version = "0.18.8";
1324
1324
  //#endregion
1325
1325
  //#region src/serve/session.ts
1326
1326
  var CapletsMcpSession = class {
@@ -7349,7 +7349,7 @@ var SSEStreamingApi = class extends StreamingApi {
7349
7349
  }
7350
7350
  };
7351
7351
  //#endregion
7352
- //#region ../../node_modules/.pnpm/@hono+mcp@0.3.0_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__hono-rate-limiter@0.5.3_hono@4.12.23__hono@4.12.23_zod@4.4.3/node_modules/@hono/mcp/dist/index.js
7352
+ //#region ../../node_modules/.pnpm/@hono+mcp@0.3.0_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__hono-rate-limiter@0.5.3_hon_db5d1ad1945c3abb4411768ead465a9b/node_modules/@hono/mcp/dist/index.js
7353
7353
  let isOldBunVersion = () => {
7354
7354
  const version = typeof Bun !== "undefined" ? Bun.version : void 0;
7355
7355
  if (version === void 0) return false;
@@ -10737,4 +10737,4 @@ function writeAddResult(writeOut, label, result) {
10737
10737
  writeOut(result.text);
10738
10738
  }
10739
10739
  //#endregion
10740
- export { CapletsRuntime, ServerRegistry, capabilityDescription, createProgram, generatedToolInputSchema, handleServerTool, loadConfig, parseConfig, runCli, serveCaplets, serveHttp, serveResolvedCaplets, serveStdio };
10740
+ export { CapletsRuntime, ServerRegistry, capabilityDescription, createProgram, generatedToolInputSchema, handleServerTool, hasRenderableStructuredContent, loadConfig, markdownCallToolResultContent, markdownStructuredContent, parseConfig, runCli, serveCaplets, serveHttp, serveResolvedCaplets, serveStdio };
package/dist/native.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Q as ToolListChangedNotificationSchema, _ as StreamableHTTPClientTransport, a as resolveCapletsServer, b as Client, bt as parseConfig, i as resolveCapletsMode, jt as CapletsError, l as capabilityDescription, n as mcpUrlForBase, o as CapletsEngine, vt as loadLocalOverlayConfigWithSources } from "./options-BlNyqF_E.js";
2
- import { a as generatedToolInputJsonSchemaForCaplet, i as generatedToolInputJsonSchema, l as operations, o as generatedToolInputSchema } from "./generated-tool-input-schema-BYoyY-l-.js";
1
+ import { Pt as CapletsError, Q as ToolListChangedNotificationSchema, _ as StreamableHTTPClientTransport, a as resolveCapletsServer, b as Client, bt as parseConfig, i as resolveCapletsMode, l as capabilityDescription, n as mcpUrlForBase, o as CapletsEngine, vt as loadLocalOverlayConfigWithSources } from "./options--RoZwWjs.js";
2
+ import { a as generatedToolInputJsonSchemaForCaplet, i as generatedToolInputJsonSchema, l as operations, o as generatedToolInputSchema } from "./generated-tool-input-schema-MbYF5jMW.js";
3
3
  //#region src/native/options.ts
4
4
  const DEFAULT_POLL_INTERVAL_MS = 3e4;
5
5
  function resolveNativeCapletsServiceOptions(input = {}, env = process.env) {
package/dist/openapi.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CompatibilityCallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
1
+ import type { CompatibilityCallToolResult, Tool } from "@modelcontextprotocol/sdk/types";
2
2
  import type { OpenApiEndpointConfig } from "./config";
3
3
  import type { CompactTool } from "./downstream";
4
4
  import type { ServerRegistry } from "./registry";
@@ -1,4 +1,4 @@
1
- import { A as url, B as clone, C as object$1, D as string, E as record, F as $ZodType, H as normalizeParams, I as parse$2, L as parseAsync, M as toJSONSchema, N as _coercedNumber, O as union, P as $ZodObject, R as safeParse$1, S as number$1, T as preprocess, U as $constructor, V as defineLazy, W as NEVER, _ as custom, b as literal, c as mcpOperations, f as _enum, g as boolean, h as array, i as generatedToolInputJsonSchema, j as datetime, k as unknown, l as operations, m as any, p as _null, s as generatedToolInputSchemaForCaplet, u as ZodNumber$1, v as discriminatedUnion, w as optional, x as looseObject, y as intersection, z as safeParseAsync$1 } from "./generated-tool-input-schema-BYoyY-l-.js";
1
+ import { A as url, B as clone, C as object$1, D as string, E as record, F as $ZodType, H as normalizeParams, I as parse$2, L as parseAsync, M as toJSONSchema, N as _coercedNumber, O as union, P as $ZodObject, R as safeParse$1, S as number$1, T as preprocess, U as $constructor, V as defineLazy, W as NEVER, _ as custom, b as literal, c as mcpOperations, f as _enum, g as boolean, h as array, i as generatedToolInputJsonSchema, j as datetime, k as unknown, l as operations, m as any, p as _null, s as generatedToolInputSchemaForCaplet, u as ZodNumber$1, v as discriminatedUnion, w as optional, x as looseObject, y as intersection, z as safeParseAsync$1 } from "./generated-tool-input-schema-MbYF5jMW.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
4
4
  import minpath, { basename, delimiter, dirname, extname, isAbsolute, join, parse, posix, relative, resolve, win32 } from "node:path";
@@ -108,13 +108,26 @@ function toSafeError(error, fallback = "INTERNAL_ERROR") {
108
108
  }
109
109
  function errorResult(error, fallback) {
110
110
  const safe = toSafeError(error, fallback);
111
+ const structuredContent = { error: safe };
111
112
  return {
112
113
  isError: true,
113
114
  content: [{
114
115
  type: "text",
115
- text: `${safe.code}: ${safe.message}`
116
+ text: [
117
+ "# Error",
118
+ "",
119
+ `## ${safe.code}`,
120
+ "",
121
+ safe.message,
122
+ "",
123
+ "## Details",
124
+ "",
125
+ "```json",
126
+ JSON.stringify(safe, null, 2),
127
+ "```"
128
+ ].join("\n")
116
129
  }],
117
- structuredContent: { error: safe }
130
+ structuredContent
118
131
  };
119
132
  }
120
133
  //#endregion
@@ -125,33 +138,277 @@ function textContent(text) {
125
138
  text
126
139
  }] : [];
127
140
  }
128
- function compactJsonText(value, maxLength = 600) {
129
- return compactText(JSON.stringify(value) ?? String(value), maxLength);
141
+ function markdownStructuredContent(value, context = {}) {
142
+ return textContent(renderStructuredMarkdown(value, context));
130
143
  }
131
- function compactText(value, maxLength = 600) {
132
- const collapsed = value.replace(/\s+/gu, " ").trim();
133
- return collapsed.length > maxLength ? `${collapsed.slice(0, maxLength - 1).trimEnd()}…` : collapsed;
144
+ function markdownCallToolResultContent(result, context = {}) {
145
+ const downstreamText = textBlocksToString(result.content);
146
+ const structuredContent = result.structuredContent;
147
+ const hasStructured = hasRenderableStructuredContent(structuredContent);
148
+ if (context.backend === "mcp" && hasStructured) {
149
+ const renderedStructured = markdownStructuredContent(structuredContent, context)[0]?.text;
150
+ if (downstreamText && downstreamText === renderedStructured) return textContent(downstreamText);
151
+ return [...result.content ?? [], {
152
+ type: "text",
153
+ text: [
154
+ "## Structured Content",
155
+ "",
156
+ jsonFence(structuredContent)
157
+ ].join("\n")
158
+ }];
159
+ }
160
+ if (hasStructured) return markdownStructuredContent(structuredContent, {
161
+ ...context,
162
+ isError: context.isError ?? result.isError
163
+ });
164
+ if (downstreamText) return textContent(downstreamText);
165
+ return textContent(renderStructuredMarkdown(result, context));
166
+ }
167
+ function hasRenderableStructuredContent(value) {
168
+ if (!isRecord(value)) return false;
169
+ return Object.keys(value).some((key) => key !== "caplets" && key !== "elapsedMs");
170
+ }
171
+ function renderStructuredMarkdown(value, context) {
172
+ const title = markdownTitle(context);
173
+ if (isDiscoveryWrapper(value)) return renderDiscoveryWrapper(value, context, title);
174
+ if (context.isError || isErrorStructuredContent(value)) return renderErrorMarkdown(value, title);
175
+ if (context.backend === "cli" || isCliResult(value)) return renderCliMarkdown(value, title);
176
+ if (context.backend === "graphql" && isHttpLikeResult(value) || isGraphQlHttpResult(value)) return renderGraphQlMarkdown(value, title);
177
+ if (isHttpLikeResult(value)) return renderHttpMarkdown(value, title);
178
+ return [
179
+ title,
180
+ "",
181
+ "## Result",
182
+ "",
183
+ jsonFence(value)
184
+ ].join("\n");
185
+ }
186
+ function markdownTitle(context) {
187
+ if (context.title) return `# ${context.title}`;
188
+ const parts = [context.operation, context.tool ?? context.uri ?? context.prompt].filter((part) => Boolean(part));
189
+ return parts.length > 0 ? `# ${parts.join(" ")}` : "# Result";
190
+ }
191
+ function renderHttpMarkdown(value, title) {
192
+ const record = asRecord$2(value) ?? {};
193
+ const lines = [
194
+ title,
195
+ "",
196
+ "## Response",
197
+ ""
198
+ ];
199
+ const status = typeof record.status === "number" ? record.status : void 0;
200
+ const statusText = typeof record.statusText === "string" ? record.statusText : void 0;
201
+ if (status !== void 0 || statusText) lines.push(`- **Status:** \`${[status, statusText].filter(Boolean).join(" ")}\``);
202
+ if (typeof record.elapsedMs === "number") lines.push(`- **Elapsed:** \`${record.elapsedMs} ms\``);
203
+ lines.push("", "## Headers", "", jsonFence(record.headers ?? {}), "", "## Body", "", renderBodyValue(record.body));
204
+ const additional = omitKeys(record, [
205
+ "status",
206
+ "statusText",
207
+ "headers",
208
+ "body",
209
+ "elapsedMs"
210
+ ]);
211
+ if (Object.keys(additional).length > 0) lines.push("", "## Additional Fields", "", jsonFence(additional));
212
+ return lines.join("\n");
213
+ }
214
+ function renderGraphQlMarkdown(value, title) {
215
+ const record = asRecord$2(value) ?? {};
216
+ const body = asRecord$2(record.body);
217
+ if (!body || !("data" in body) && !("errors" in body)) return renderHttpMarkdown(value, title);
218
+ const lines = [
219
+ title,
220
+ "",
221
+ "## Response",
222
+ ""
223
+ ];
224
+ const status = typeof record.status === "number" ? record.status : void 0;
225
+ const statusText = typeof record.statusText === "string" ? record.statusText : void 0;
226
+ if (status !== void 0 || statusText) lines.push(`- **Status:** \`${[status, statusText].filter(Boolean).join(" ")}\``);
227
+ if (typeof record.elapsedMs === "number") lines.push(`- **Elapsed:** \`${record.elapsedMs} ms\``);
228
+ if ("data" in body) lines.push("", "## Data", "", jsonFence(body.data));
229
+ if ("errors" in body) lines.push("", "## Errors", "", jsonFence(body.errors));
230
+ lines.push("", "## Headers", "", jsonFence(record.headers ?? {}), "", "## Full Body", "", jsonFence(record.body));
231
+ const additional = omitKeys(record, [
232
+ "status",
233
+ "statusText",
234
+ "headers",
235
+ "body",
236
+ "elapsedMs"
237
+ ]);
238
+ if (Object.keys(additional).length > 0) lines.push("", "## Additional Fields", "", jsonFence(additional));
239
+ return lines.join("\n");
240
+ }
241
+ function renderCliMarkdown(value, title) {
242
+ const record = asRecord$2(value) ?? {};
243
+ const lines = [
244
+ title,
245
+ "",
246
+ "## Command Result",
247
+ ""
248
+ ];
249
+ if ("exitCode" in record) lines.push(`- **Exit code:** \`${String(record.exitCode)}\``);
250
+ if ("signal" in record) lines.push(`- **Signal:** \`${String(record.signal)}\``);
251
+ if (typeof record.elapsedMs === "number") lines.push(`- **Elapsed:** \`${record.elapsedMs} ms\``);
252
+ lines.push("", "## stdout", "", textFenceOrEmpty(record.stdout, "No stdout."));
253
+ lines.push("", "## stderr", "", textFenceOrEmpty(record.stderr, "No stderr."));
254
+ if ("json" in record) lines.push("", "## Parsed JSON", "", jsonFence(record.json));
255
+ if ("jsonParseError" in record) lines.push("", "## JSON Parse Error", "", jsonFence(record.jsonParseError));
256
+ const additional = omitKeys(record, [
257
+ "exitCode",
258
+ "signal",
259
+ "stdout",
260
+ "stderr",
261
+ "elapsedMs",
262
+ "json",
263
+ "jsonParseError"
264
+ ]);
265
+ if (Object.keys(additional).length > 0) lines.push("", "## Additional Fields", "", jsonFence(additional));
266
+ return lines.join("\n");
267
+ }
268
+ function renderDiscoveryWrapper(value, context, title) {
269
+ const result = asRecord$2(value.result);
270
+ const lines = [title, ""];
271
+ if (context.operation === "list_tools" || context.operation === "search_tools") lines.push("## Tools", "", renderNamedList(arrayValue(result?.tools), "tool"), "");
272
+ else if (context.operation === "list_resources" || context.operation === "search_resources") lines.push("## Resources", "", renderNamedList(arrayValue(result?.resources ?? result?.matches), "uri"), "");
273
+ else if (context.operation === "list_resource_templates") lines.push("## Resource Templates", "", renderNamedList(arrayValue(result?.resourceTemplates), "uriTemplate"), "");
274
+ else if (context.operation === "list_prompts" || context.operation === "search_prompts") lines.push("## Prompts", "", renderNamedList(arrayValue(result?.prompts), "prompt"), "");
275
+ else if (context.operation === "get_tool") lines.push("## Tool", "", renderToolSummary(asRecord$2(result?.tool)), "");
276
+ else if (context.operation === "check_backend") lines.push("## Backend Status", "", renderBackendStatus(result), "");
277
+ else if (context.operation === "get_caplet") lines.push("## Caplet", "", renderCapletSummary(result), "");
278
+ lines.push("## Full Result", "", jsonFence(value.result));
279
+ if (value.caplets !== void 0) lines.push("", "## Caplets Metadata", "", jsonFence(value.caplets));
280
+ return lines.join("\n");
281
+ }
282
+ function renderErrorMarkdown(value, title) {
283
+ const error = asRecord$2(asRecord$2(value)?.error) ?? asRecord$2(value);
284
+ const code = typeof error?.code === "string" ? error.code : "Error";
285
+ const message = typeof error?.message === "string" ? error.message : "Tool call failed.";
286
+ return [
287
+ title === "# Result" || title === "# Error" ? "# Error" : title,
288
+ "",
289
+ `## ${code}`,
290
+ "",
291
+ message,
292
+ "",
293
+ "## Details",
294
+ "",
295
+ jsonFence(error ?? value)
296
+ ].join("\n");
297
+ }
298
+ function isDiscoveryWrapper(value) {
299
+ return isRecord(value) && "result" in value;
134
300
  }
135
- function resultKeys(value) {
136
- if (!value || typeof value !== "object" || Array.isArray(value)) return "scalar result";
137
- const keys = Object.keys(value).filter((key) => key !== "elapsedMs");
138
- return keys.length > 0 ? `structured keys: ${keys.join(", ")}` : "empty structured result";
301
+ function isErrorStructuredContent(value) {
302
+ return isRecord(value) && "error" in value;
139
303
  }
140
- function statusSummary(value) {
141
- if (!value || typeof value !== "object" || Array.isArray(value)) return compactJsonText(value);
142
- const record = value;
304
+ function isHttpLikeResult(value) {
305
+ return isRecord(value) && ("status" in value || "statusText" in value || "body" in value);
306
+ }
307
+ function isGraphQlHttpResult(value) {
308
+ if (!isHttpLikeResult(value)) return false;
309
+ const body = asRecord$2(value.body);
310
+ return Boolean(body && ("data" in body || "errors" in body));
311
+ }
312
+ function isCliResult(value) {
313
+ return isRecord(value) && ("exitCode" in value || "stdout" in value || "stderr" in value);
314
+ }
315
+ function renderBodyValue(value) {
316
+ if (value === void 0) return "_No response body._";
317
+ if (typeof value === "string") return textFenceOrEmpty(value, "No response body.");
318
+ return jsonFence(value);
319
+ }
320
+ function textFenceOrEmpty(value, emptyMessage) {
321
+ if (typeof value !== "string" || value.length === 0) return `_${emptyMessage}_`;
143
322
  return [
144
- typeof record.status === "number" ? `status ${record.status}` : void 0,
145
- typeof record.statusText === "string" && record.statusText ? record.statusText : void 0,
146
- typeof record.exitCode === "number" ? `exit ${record.exitCode}` : void 0,
147
- "body" in record ? "body" : void 0,
148
- "json" in record ? "json" : void 0,
149
- typeof record.stdout === "string" && record.stdout ? "stdout" : void 0,
150
- typeof record.stderr === "string" && record.stderr ? "stderr" : void 0
151
- ].filter((part) => Boolean(part)).join("; ") || resultKeys(record);
323
+ "```text",
324
+ escapeCodeFence(value),
325
+ "```"
326
+ ].join("\n");
327
+ }
328
+ function jsonFence(value) {
329
+ return [
330
+ "```json",
331
+ escapeCodeFence(JSON.stringify(value, null, 2) ?? "null"),
332
+ "```"
333
+ ].join("\n");
334
+ }
335
+ function escapeCodeFence(value) {
336
+ return value.replace(/```/gu, "`​``");
337
+ }
338
+ function textBlocksToString(content) {
339
+ if (!Array.isArray(content)) return "";
340
+ return content.filter((item) => Boolean(item && typeof item === "object" && item.type === "text" && typeof item.text === "string")).map((item) => item.text).filter(Boolean).join("\n");
341
+ }
342
+ function renderNamedList(items, nameKey) {
343
+ if (items.length === 0) return "_No items._";
344
+ return items.map((item, index) => {
345
+ const record = asRecord$2(item);
346
+ const name = stringValue(record?.[nameKey]) ?? stringValue(record?.name) ?? `Item ${index + 1}`;
347
+ const description = stringValue(record?.description);
348
+ return description ? `${index + 1}. \`${name}\` — ${description}` : `${index + 1}. \`${name}\``;
349
+ }).join("\n");
350
+ }
351
+ function renderToolSummary(tool) {
352
+ if (!tool) return "_Tool details unavailable._";
353
+ const lines = [];
354
+ const name = stringValue(tool.name);
355
+ const description = stringValue(tool.description);
356
+ if (name) lines.push(`- **Name:** \`${name}\``);
357
+ if (description) lines.push(`- **Description:** ${description}`);
358
+ if (tool.inputSchema !== void 0) lines.push("", "### Input Schema", "", jsonFence(tool.inputSchema));
359
+ if (tool.outputSchema !== void 0) lines.push("", "### Output Schema", "", jsonFence(tool.outputSchema));
360
+ if (tool.annotations !== void 0) lines.push("", "### Annotations", "", jsonFence(tool.annotations));
361
+ return lines.length > 0 ? lines.join("\n") : jsonFence(tool);
362
+ }
363
+ function renderBackendStatus(result) {
364
+ if (!result) return "_Backend status unavailable._";
365
+ const lines = [];
366
+ for (const key of [
367
+ "id",
368
+ "status",
369
+ "toolCount",
370
+ "resourceCount",
371
+ "resourceTemplateCount",
372
+ "promptCount",
373
+ "elapsedMs"
374
+ ]) if (result[key] !== void 0) {
375
+ const label = key === "elapsedMs" ? "Elapsed" : humanizeKey(key);
376
+ const suffix = key === "elapsedMs" ? " ms" : "";
377
+ lines.push(`- **${label}:** \`${String(result[key])}${suffix}\``);
378
+ }
379
+ if (result.error !== void 0) lines.push("", "### Error", "", jsonFence(result.error));
380
+ return lines.length > 0 ? lines.join("\n") : jsonFence(result);
381
+ }
382
+ function renderCapletSummary(result) {
383
+ if (!result) return "_Caplet details unavailable._";
384
+ const lines = [];
385
+ for (const key of [
386
+ "id",
387
+ "name",
388
+ "description"
389
+ ]) if (result[key] !== void 0) lines.push(`- **${humanizeKey(key)}:** ${String(result[key])}`);
390
+ const backend = asRecord$2(result.backend);
391
+ if (backend?.type !== void 0) lines.push(`- **Backend:** \`${String(backend.type)}\``);
392
+ return lines.length > 0 ? lines.join("\n") : jsonFence(result);
393
+ }
394
+ function omitKeys(record, keys) {
395
+ const omitted = new Set(keys);
396
+ return Object.fromEntries(Object.entries(record).filter(([key]) => !omitted.has(key)));
397
+ }
398
+ function arrayValue(value) {
399
+ return Array.isArray(value) ? value : [];
400
+ }
401
+ function stringValue(value) {
402
+ return typeof value === "string" && value.length > 0 ? value : void 0;
403
+ }
404
+ function humanizeKey(key) {
405
+ return key.replace(/([A-Z])/gu, " $1").replace(/^./u, (char) => char.toUpperCase());
152
406
  }
153
- function compactStructuredContent(value) {
154
- return textContent(statusSummary(value));
407
+ function asRecord$2(value) {
408
+ return isRecord(value) ? value : void 0;
409
+ }
410
+ function isRecord(value) {
411
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
155
412
  }
156
413
  //#endregion
157
414
  //#region src/tool-search.ts
@@ -222,7 +479,12 @@ var CliToolsManager = class {
222
479
  const result = await spawnCommand(execution, controller.signal, () => Date.now() - startedAt);
223
480
  const structured = parseStructuredResult(action, result, result.exitCode !== 0);
224
481
  return {
225
- content: compactStructuredContent(structured),
482
+ content: markdownStructuredContent(structured, {
483
+ title: `${config.name} call_tool ${toolName}`,
484
+ backend: "cli",
485
+ operation: "call_tool",
486
+ tool: toolName
487
+ }),
226
488
  structuredContent: structured,
227
489
  isError: result.exitCode !== 0
228
490
  };
@@ -442,7 +704,7 @@ const ZodIssueCode$1 = {
442
704
  };
443
705
  /** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
444
706
  var ZodFirstPartyTypeKind$1;
445
- (function(ZodFirstPartyTypeKind) {})(ZodFirstPartyTypeKind$1 || (ZodFirstPartyTypeKind$1 = {}));
707
+ ZodFirstPartyTypeKind$1 || (ZodFirstPartyTypeKind$1 = {});
446
708
  //#endregion
447
709
  //#region ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js
448
710
  function number(params) {
@@ -13201,7 +13463,7 @@ ZodEffects.createWithPreprocess;
13201
13463
  ZodPipeline.create;
13202
13464
  //#endregion
13203
13465
  //#region ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/mini/schemas.js
13204
- const ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {
13466
+ const ZodMiniType = /*@__PURE__*/ $constructor("ZodMiniType", (inst, def) => {
13205
13467
  if (!inst._zod) throw new Error("Uninitialized schema in ZodMiniType.");
13206
13468
  $ZodType.init(inst, def);
13207
13469
  inst.def = def;
@@ -13229,12 +13491,12 @@ const ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {
13229
13491
  });
13230
13492
  inst.apply = (fn) => fn(inst);
13231
13493
  });
13232
- const ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => {
13494
+ const ZodMiniObject = /*@__PURE__*/ $constructor("ZodMiniObject", (inst, def) => {
13233
13495
  $ZodObject.init(inst, def);
13234
13496
  ZodMiniType.init(inst, def);
13235
13497
  defineLazy(inst, "shape", () => def.shape);
13236
13498
  });
13237
- /* @__NO_SIDE_EFFECTS__ */
13499
+ // @__NO_SIDE_EFFECTS__
13238
13500
  function object(shape, params) {
13239
13501
  return new ZodMiniObject({
13240
13502
  type: "object",
@@ -15702,7 +15964,7 @@ function parseStringDef(def, refs) {
15702
15964
  case "toLowerCase":
15703
15965
  case "toUpperCase":
15704
15966
  case "trim": break;
15705
- default: ((_) => {})(check);
15967
+ default:
15706
15968
  }
15707
15969
  return res;
15708
15970
  }
@@ -42654,7 +42916,12 @@ var GraphQLManager = class {
42654
42916
  body
42655
42917
  };
42656
42918
  return {
42657
- content: compactStructuredContent(result),
42919
+ content: markdownStructuredContent(result, {
42920
+ title: `${endpoint.name} call_tool ${toolName}`,
42921
+ backend: "graphql",
42922
+ operation: "call_tool",
42923
+ tool: toolName
42924
+ }),
42658
42925
  structuredContent: result,
42659
42926
  isError: !response.ok || Boolean(body && typeof body === "object" && "errors" in body && body.errors)
42660
42927
  };
@@ -43048,7 +43315,12 @@ var HttpActionManager = class {
43048
43315
  });
43049
43316
  const parsed = await readResponse$1(response, api, Date.now() - startedAt);
43050
43317
  return {
43051
- content: compactStructuredContent(parsed),
43318
+ content: markdownStructuredContent(parsed, {
43319
+ title: `${api.name} call_tool ${toolName}`,
43320
+ backend: "http",
43321
+ operation: "call_tool",
43322
+ tool: toolName
43323
+ }),
43052
43324
  structuredContent: parsed,
43053
43325
  isError: !response.ok
43054
43326
  };
@@ -52839,7 +53111,12 @@ var OpenApiManager = class {
52839
53111
  });
52840
53112
  const parsed = await readResponse(response);
52841
53113
  return {
52842
- content: compactStructuredContent(parsed),
53114
+ content: markdownStructuredContent(parsed, {
53115
+ title: `${endpoint.name} call_tool ${toolName}`,
53116
+ backend: "openapi",
53117
+ operation: "call_tool",
53118
+ tool: toolName
53119
+ }),
52843
53120
  structuredContent: parsed,
52844
53121
  isError: response.ok ? false : true
52845
53122
  };
@@ -53476,7 +53753,8 @@ async function handleServerTool(server, request, registry, downstream, openapi,
53476
53753
  const tool = await backend.getTool(server, parsed.tool);
53477
53754
  if (!tool.outputSchema) throw new CapletsError("REQUEST_INVALID", "Field selection requires an output schema");
53478
53755
  validateFieldSelection(tool.outputSchema, parsed.fields);
53479
- return annotateCallToolResult(projectCallToolResult(await backend.callTool(server, parsed.tool, parsed.arguments), tool.outputSchema, parsed.fields), metadataFor(server, "call_tool", parsed.tool, startedAt));
53756
+ const metadata = metadataFor(server, "call_tool", parsed.tool, startedAt);
53757
+ return annotateCallToolResult(projectCallToolResult(await backend.callTool(server, parsed.tool, parsed.arguments), tool.outputSchema, parsed.fields, markdownContextFor(metadata)), metadata);
53480
53758
  }
53481
53759
  case "list_resources": {
53482
53760
  const backend = mcpBackendFor(server, downstream);
@@ -53680,16 +53958,28 @@ function annotateMcpResult(result, metadata) {
53680
53958
  }
53681
53959
  };
53682
53960
  }
53961
+ function markdownContextFor(metadata) {
53962
+ return {
53963
+ title: [
53964
+ metadata.name,
53965
+ metadata.operation,
53966
+ metadata.tool ?? metadata.uri ?? metadata.prompt
53967
+ ].filter(Boolean).join(" "),
53968
+ backend: metadata.backend,
53969
+ operation: metadata.operation,
53970
+ ...metadata.tool ? { tool: metadata.tool } : {},
53971
+ ...metadata.uri ? { uri: metadata.uri } : {},
53972
+ ...metadata.prompt ? { prompt: metadata.prompt } : {}
53973
+ };
53974
+ }
53683
53975
  function jsonResult(value, metadata) {
53976
+ const structuredContent = {
53977
+ ...metadata === void 0 ? {} : { caplets: metadata },
53978
+ result: value
53979
+ };
53684
53980
  return {
53685
- content: [{
53686
- type: "text",
53687
- text: JSON.stringify(value, null, 2)
53688
- }],
53689
- structuredContent: {
53690
- ...metadata === void 0 ? {} : { caplets: metadata },
53691
- result: value
53692
- }
53981
+ content: markdownStructuredContent(structuredContent, metadata ? markdownContextFor(metadata) : { title: "Result" }),
53982
+ structuredContent
53693
53983
  };
53694
53984
  }
53695
53985
  function annotateCallToolResult(result, metadata) {
@@ -53702,20 +53992,21 @@ function annotateCallToolResult(result, metadata) {
53702
53992
  };
53703
53993
  return {
53704
53994
  ...result,
53995
+ content: markdownCallToolResultContent(result, markdownContextFor(annotatedMetadata)),
53705
53996
  _meta: {
53706
53997
  ...isPlainObject(existingMeta) ? existingMeta : {},
53707
53998
  caplets: annotatedMetadata
53708
53999
  }
53709
54000
  };
53710
54001
  }
53711
- function projectCallToolResult(result, outputSchema, fields) {
54002
+ function projectCallToolResult(result, outputSchema, fields, context = {}) {
53712
54003
  if (result.isError === true) return result;
53713
54004
  const structuredContent = result.structuredContent;
53714
54005
  if (!isPlainObject(structuredContent)) throw new CapletsError("DOWNSTREAM_PROTOCOL_ERROR", "Field selection requires the downstream tool to return object structuredContent");
53715
54006
  const projected = projectStructuredContent(structuredContent, outputSchema, fields);
53716
54007
  return {
53717
54008
  ...result,
53718
- content: compactStructuredContent(projected),
54009
+ content: markdownStructuredContent(projected, context),
53719
54010
  structuredContent: projected
53720
54011
  };
53721
54012
  }
@@ -54154,7 +54445,7 @@ var CapletsEngine = class {
54154
54445
  }
54155
54446
  }
54156
54447
  async completeCliWords(words) {
54157
- const { completeCliWords } = await import("./completion-DRPTunQd.js").then((n) => n.r);
54448
+ const { completeCliWords } = await import("./completion-DvWQk5qR.js").then((n) => n.r);
54158
54449
  return await completeCliWords(words, {
54159
54450
  config: this.registry.config,
54160
54451
  managers: {
@@ -54494,4 +54785,4 @@ function hasEnv(value) {
54494
54785
  return value !== void 0 && value.trim() !== "";
54495
54786
  }
54496
54787
  //#endregion
54497
- export { assertCompleteRequestPrompt as $, CreateMessageResultSchema as A, CAPLETS_ERROR_CODES as At, JSONRPCMessageSchema as B, AjvJsonSchemaValidator as C, resolveCapletsRoot as Ct, CallToolRequestSchema as D, discoverCapletFiles as Dt, toJsonSchemaCompat as E, resolveProjectConfigPath as Et, EmptyResultSchema as F, __exportAll as Ft, ListRootsResultSchema as G, ListPromptsRequestSchema as H, ErrorCode as I, __require as It, McpError as J, ListToolsRequestSchema as K, GetPromptRequestSchema as L, __toESM as Lt, CreateTaskResultSchema as M, redactSecrets as Mt, DEFAULT_NEGOTIATED_PROTOCOL_VERSION as N, toSafeError as Nt, CallToolResultSchema as O, validateCapletFile as Ot, ElicitResultSchema as P, __commonJSMin as Pt, ToolListChangedNotificationSchema as Q, InitializeRequestSchema as R, assertToolsCallTaskCapability as S, DEFAULT_COMPLETION_CACHE_DIR as St, mergeCapabilities as T, resolveProjectCapletsRoot as Tt, ListResourceTemplatesRequestSchema as U, LATEST_PROTOCOL_VERSION as V, ListResourcesRequestSchema as W, SUPPORTED_PROTOCOL_VERSIONS as X, ReadResourceRequestSchema as Y, SetLevelRequestSchema as Z, StreamableHTTPClientTransport as _, loadGlobalConfig as _t, resolveCapletsServer as a, getLiteralValue as at, Client as b, parseConfig as bt, ServerRegistry as c, getSchemaDescription as ct, runOAuthFlow as d, normalizeObjectSchema as dt, assertCompleteRequestResourceTemplate as et, startGenericOAuthFlow as f, objectFromShape as ft, readTokenBundle as g, loadConfigWithSources as gt, isTokenBundleExpired as h, loadConfig as ht, resolveCapletsMode as i, isJSONRPCResultResponse as it, CreateMessageResultWithToolsSchema as j, CapletsError as jt, CompleteRequestSchema as k, SERVER_ID_PATTERN as kt, capabilityDescription as l, isSchemaOptional as lt, deleteTokenBundle as m, safeParseAsync as mt, mcpUrlForBase as n, isJSONRPCErrorResponse as nt, CapletsEngine as o, getObjectShape as ot, startOAuthFlow as p, safeParse as pt, LoggingLevelSchema as q, parseServerBaseUrl as r, isJSONRPCRequest as rt, handleServerTool as s, getParseErrorMessage as st, controlUrlForBase as t, isInitializeRequest as tt, runGenericOAuthFlow as u, isZ4Schema as ut, ReadBuffer as v, loadLocalOverlayConfigWithSources as vt, Protocol as w, resolveConfigPath as wt, assertClientRequestTaskCapability as x, DEFAULT_AUTH_DIR as xt, serializeMessage as y, loadProjectConfig as yt, InitializedNotificationSchema as z };
54788
+ export { assertCompleteRequestPrompt as $, CreateMessageResultSchema as A, hasRenderableStructuredContent as At, JSONRPCMessageSchema as B, __toESM as Bt, AjvJsonSchemaValidator as C, resolveCapletsRoot as Ct, CallToolRequestSchema as D, discoverCapletFiles as Dt, toJsonSchemaCompat as E, resolveProjectConfigPath as Et, EmptyResultSchema as F, redactSecrets as Ft, ListRootsResultSchema as G, ListPromptsRequestSchema as H, ErrorCode as I, toSafeError as It, McpError as J, ListToolsRequestSchema as K, GetPromptRequestSchema as L, __commonJSMin as Lt, CreateTaskResultSchema as M, markdownStructuredContent as Mt, DEFAULT_NEGOTIATED_PROTOCOL_VERSION as N, CAPLETS_ERROR_CODES as Nt, CallToolResultSchema as O, validateCapletFile as Ot, ElicitResultSchema as P, CapletsError as Pt, ToolListChangedNotificationSchema as Q, InitializeRequestSchema as R, __exportAll as Rt, assertToolsCallTaskCapability as S, DEFAULT_COMPLETION_CACHE_DIR as St, mergeCapabilities as T, resolveProjectCapletsRoot as Tt, ListResourceTemplatesRequestSchema as U, LATEST_PROTOCOL_VERSION as V, ListResourcesRequestSchema as W, SUPPORTED_PROTOCOL_VERSIONS as X, ReadResourceRequestSchema as Y, SetLevelRequestSchema as Z, StreamableHTTPClientTransport as _, loadGlobalConfig as _t, resolveCapletsServer as a, getLiteralValue as at, Client as b, parseConfig as bt, ServerRegistry as c, getSchemaDescription as ct, runOAuthFlow as d, normalizeObjectSchema as dt, assertCompleteRequestResourceTemplate as et, startGenericOAuthFlow as f, objectFromShape as ft, readTokenBundle as g, loadConfigWithSources as gt, isTokenBundleExpired as h, loadConfig as ht, resolveCapletsMode as i, isJSONRPCResultResponse as it, CreateMessageResultWithToolsSchema as j, markdownCallToolResultContent as jt, CompleteRequestSchema as k, SERVER_ID_PATTERN as kt, capabilityDescription as l, isSchemaOptional as lt, deleteTokenBundle as m, safeParseAsync as mt, mcpUrlForBase as n, isJSONRPCErrorResponse as nt, CapletsEngine as o, getObjectShape as ot, startOAuthFlow as p, safeParse as pt, LoggingLevelSchema as q, parseServerBaseUrl as r, isJSONRPCRequest as rt, handleServerTool as s, getParseErrorMessage as st, controlUrlForBase as t, isInitializeRequest as tt, runGenericOAuthFlow as u, isZ4Schema as ut, ReadBuffer as v, loadLocalOverlayConfigWithSources as vt, Protocol as w, resolveConfigPath as wt, assertClientRequestTaskCapability as x, DEFAULT_AUTH_DIR as xt, serializeMessage as y, loadProjectConfig as yt, InitializedNotificationSchema as z, __require as zt };