@almyty/mcp-server 1.5.1 → 1.5.3

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/dist/proxy.js CHANGED
@@ -1,7 +1,55 @@
1
1
  /**
2
2
  * HTTP proxy to the almyty backend.
3
3
  * Fetches tools and executes tool calls via the MCP JSON-RPC API.
4
+ *
5
+ * Upstream, the proxy is an MCP client of almyty's own protocol core. It
6
+ * speaks MCP 2026-07-28 there by default: every request names its version,
7
+ * capabilities and client in `_meta` and mirrors them in the
8
+ * `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` headers. An almyty
9
+ * backend from before 2026-07-28 refuses that version with a 400; the proxy
10
+ * then switches to the request shape it always sent (no version header,
11
+ * no `_meta`) and stays there for the life of the process. `skills/list` is
12
+ * almyty's own method, which the 2026-07-28 core does not serve, so it is
13
+ * always asked the legacy way.
14
+ *
15
+ * ALMYTY_MCP_PROTOCOL pins the choice: `modern`, `legacy`, or `auto`
16
+ * (default).
4
17
  */
18
+ export const MODERN_PROTOCOL_VERSION = '2026-07-28';
19
+ /** ALMYTY_MCP_PROTOCOL, read leniently: anything unknown is `auto`. */
20
+ export function upstreamEraFromEnv(value = process.env.ALMYTY_MCP_PROTOCOL) {
21
+ const v = (value ?? '').trim().toLowerCase();
22
+ return v === 'modern' || v === 'legacy' ? v : 'auto';
23
+ }
24
+ /**
25
+ * A header value as MCP 2026-07-28 carries it: as is when it is plain
26
+ * printable ASCII with no surrounding whitespace, otherwise the Base64
27
+ * sentinel `=?base64?...?=` of its UTF-8 bytes.
28
+ */
29
+ export function encodeMcpHeaderValue(value) {
30
+ const plain = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/.test(value) && !value.startsWith('=?base64?');
31
+ return plain ? value : `=?base64?${Buffer.from(value, 'utf8').toString('base64')}?=`;
32
+ }
33
+ /** Methods whose `Mcp-Name` header mirrors a body field. */
34
+ const NAME_FIELD = { 'tools/call': 'name', 'prompts/get': 'name', 'resources/read': 'uri' };
35
+ /** Methods almyty serves only to legacy requests (its own, not in the 2026-07-28 method table). */
36
+ const LEGACY_ONLY_METHODS = new Set(['skills/list']);
37
+ /**
38
+ * Whether an answer to a modern request says "this server does not speak
39
+ * 2026-07-28": the 400 a backend from before it gives an unknown
40
+ * MCP-Protocol-Version (-32600 naming the version), or the 2026 code for it
41
+ * (-32022).
42
+ */
43
+ export function isEraRefusal(status, body) {
44
+ if (status !== 400)
45
+ return false;
46
+ const error = body?.error;
47
+ if (!error || typeof error.code !== 'number')
48
+ return false;
49
+ if (error.code === -32022)
50
+ return true;
51
+ return error.code === -32600 && /protocol version/i.test(String(error.message ?? ''));
52
+ }
5
53
  /** Default timeout for backend calls (ms). Tool execution is intentionally
6
54
  * longer than discovery because the LLM may be invoking a long-running tool. */
7
55
  const DEFAULT_DISCOVERY_TIMEOUT_MS = 15_000;
@@ -13,6 +61,10 @@ export class AlmytyProxy {
13
61
  discoveryTimeoutMs;
14
62
  toolTimeoutMs;
15
63
  warn;
64
+ configuredEra;
65
+ clientVersion;
66
+ /** The era the upstream turned out to speak; null until a request has told. */
67
+ resolvedEra = null;
16
68
  requestSeq = 0;
17
69
  constructor(baseUrl, token, gatewayId, options = {}) {
18
70
  this.baseUrl = baseUrl.replace(/\/$/, '');
@@ -22,6 +74,14 @@ export class AlmytyProxy {
22
74
  this.toolTimeoutMs = options.toolTimeoutMs ?? DEFAULT_TOOL_TIMEOUT_MS;
23
75
  // Default warning sink: stderr (stdout is reserved for the MCP protocol).
24
76
  this.warn = options.warn ?? ((m) => process.stderr.write(`[almyty mcp-server] ${m}\n`));
77
+ this.configuredEra = options.era ?? 'auto';
78
+ this.clientVersion = options.clientVersion ?? '0.0.0';
79
+ }
80
+ /** The era upstream requests are sent in now. */
81
+ get upstreamEra() {
82
+ if (this.configuredEra !== 'auto')
83
+ return this.configuredEra;
84
+ return this.resolvedEra ?? 'modern';
25
85
  }
26
86
  endpoint() {
27
87
  // Per-gateway scoping uses the GitHub-style route (/:orgSlug/:gatewaySlug),
@@ -34,28 +94,57 @@ export class AlmytyProxy {
34
94
  nextId() {
35
95
  return ++this.requestSeq;
36
96
  }
97
+ /** The body and headers of one JSON-RPC request in an era. */
98
+ request(method, params, era) {
99
+ const headers = {
100
+ 'Content-Type': 'application/json',
101
+ 'Authorization': `Bearer ${this.token}`,
102
+ };
103
+ if (era === 'legacy') {
104
+ return { headers, body: { jsonrpc: '2.0', id: this.nextId(), method, params } };
105
+ }
106
+ headers['Accept'] = 'application/json, text/event-stream';
107
+ headers['MCP-Protocol-Version'] = MODERN_PROTOCOL_VERSION;
108
+ headers['Mcp-Method'] = method;
109
+ const field = NAME_FIELD[method];
110
+ if (field && typeof params[field] === 'string')
111
+ headers['Mcp-Name'] = encodeMcpHeaderValue(params[field]);
112
+ const meta = {
113
+ 'io.modelcontextprotocol/protocolVersion': MODERN_PROTOCOL_VERSION,
114
+ 'io.modelcontextprotocol/clientCapabilities': {},
115
+ 'io.modelcontextprotocol/clientInfo': { name: '@almyty/mcp-server', version: this.clientVersion },
116
+ };
117
+ return { headers, body: { jsonrpc: '2.0', id: this.nextId(), method, params: { ...params, _meta: meta } } };
118
+ }
37
119
  /**
38
- * Wrap a fetch with an AbortSignal-based timeout. Without this, a hung
120
+ * One POST with an AbortSignal-based timeout. Without this, a hung
39
121
  * backend (e.g., a load-balancer black-hole) would hang the MCP server
40
122
  * indefinitely with no signal to the LLM client.
41
123
  */
42
- async fetchWithTimeout(method, body, timeoutMs) {
124
+ async post(label, method, params, era, timeoutMs) {
125
+ const { headers, body } = this.request(method, params, era);
43
126
  const controller = new AbortController();
44
127
  const timer = setTimeout(() => controller.abort(), timeoutMs);
45
128
  try {
46
- return await fetch(this.endpoint(), {
129
+ const response = await fetch(this.endpoint(), {
47
130
  method: 'POST',
48
- headers: {
49
- 'Content-Type': 'application/json',
50
- 'Authorization': `Bearer ${this.token}`,
51
- },
131
+ headers,
52
132
  body: JSON.stringify(body),
53
133
  signal: controller.signal,
54
134
  });
135
+ const text = await response.text().catch(() => '');
136
+ let parsed = null;
137
+ try {
138
+ parsed = text ? JSON.parse(text) : null;
139
+ }
140
+ catch {
141
+ parsed = null;
142
+ }
143
+ return { ok: response.ok, status: response.status, body: parsed, text };
55
144
  }
56
145
  catch (err) {
57
146
  if (err?.name === 'AbortError') {
58
- throw new Error(`almyty backend ${method} timed out after ${Math.round(timeoutMs / 1000)}s`);
147
+ throw new Error(`almyty backend ${label} timed out after ${Math.round(timeoutMs / 1000)}s`);
59
148
  }
60
149
  throw err;
61
150
  }
@@ -64,20 +153,31 @@ export class AlmytyProxy {
64
153
  }
65
154
  }
66
155
  /**
67
- * Fetch available tools from the almyty backend.
156
+ * A JSON-RPC call upstream in the current era, falling back to legacy once
157
+ * when the backend refuses 2026-07-28 (in `auto` mode only).
158
+ */
159
+ async rpc(label, method, params, timeoutMs) {
160
+ const era = LEGACY_ONLY_METHODS.has(method) ? 'legacy' : this.upstreamEra;
161
+ const answer = await this.post(label, method, params, era, timeoutMs);
162
+ if (era === 'modern' && this.configuredEra === 'auto' && isEraRefusal(answer.status, answer.body)) {
163
+ this.resolvedEra = 'legacy';
164
+ this.warn('the almyty backend does not speak MCP 2026-07-28 yet; using the earlier protocol');
165
+ return this.post(label, method, params, 'legacy', timeoutMs);
166
+ }
167
+ if (era === 'modern' && answer.ok && this.configuredEra === 'auto')
168
+ this.resolvedEra = 'modern';
169
+ return answer;
170
+ }
171
+ /**
172
+ * Fetch available tools from the almyty backend, with everything the
173
+ * gateway says about each: title, schemas, annotations, icons.
68
174
  */
69
175
  async fetchTools() {
70
- const response = await this.fetchWithTimeout('tools/list', {
71
- jsonrpc: '2.0',
72
- id: this.nextId(),
73
- method: 'tools/list',
74
- params: {},
75
- }, this.discoveryTimeoutMs);
76
- if (!response.ok) {
77
- const text = await response.text().catch(() => '');
78
- throw new Error(`Failed to fetch tools (${response.status}): ${text}`);
176
+ const answer = await this.rpc('tools/list', 'tools/list', {}, this.discoveryTimeoutMs);
177
+ if (!answer.ok) {
178
+ throw new Error(`Failed to fetch tools (${answer.status}): ${answer.text}`);
79
179
  }
80
- const data = await response.json();
180
+ const data = answer.body ?? {};
81
181
  if (data.error) {
82
182
  throw new Error(`MCP error: ${data.error.message}`);
83
183
  }
@@ -89,14 +189,9 @@ export class AlmytyProxy {
89
189
  * without skills (the user just won't have prompt-based guidance).
90
190
  */
91
191
  async fetchSkills() {
92
- let response;
192
+ let answer;
93
193
  try {
94
- response = await this.fetchWithTimeout('skills/list', {
95
- jsonrpc: '2.0',
96
- id: this.nextId(),
97
- method: 'skills/list',
98
- params: { limit: 100 },
99
- }, this.discoveryTimeoutMs);
194
+ answer = await this.rpc('skills/list', 'skills/list', { limit: 100 }, this.discoveryTimeoutMs);
100
195
  }
101
196
  catch (err) {
102
197
  // Previously this swallowed the error and returned []. Surface it
@@ -105,12 +200,11 @@ export class AlmytyProxy {
105
200
  this.warn(`skills/list failed: ${err?.message ?? err}`);
106
201
  return [];
107
202
  }
108
- if (!response.ok) {
109
- const text = await response.text().catch(() => '');
110
- this.warn(`skills/list returned HTTP ${response.status}: ${text.slice(0, 200)}`);
203
+ if (!answer.ok) {
204
+ this.warn(`skills/list returned HTTP ${answer.status}: ${answer.text.slice(0, 200)}`);
111
205
  return [];
112
206
  }
113
- const data = await response.json().catch(() => ({}));
207
+ const data = answer.body ?? {};
114
208
  if (data.error) {
115
209
  this.warn(`skills/list MCP error: ${data.error.message}`);
116
210
  return [];
@@ -118,40 +212,41 @@ export class AlmytyProxy {
118
212
  return data.result?.skills || [];
119
213
  }
120
214
  /**
121
- * Execute a tool call via the almyty backend.
215
+ * Execute a tool call via the almyty backend and return its result as
216
+ * the gateway gave it: content blocks, structured content, isError.
122
217
  */
123
- async callTool(toolName, args) {
124
- const response = await this.fetchWithTimeout(`tools/call ${toolName}`, {
125
- jsonrpc: '2.0',
126
- id: this.nextId(),
127
- method: 'tools/call',
128
- params: {
129
- name: toolName,
130
- arguments: args,
131
- },
132
- }, this.toolTimeoutMs);
133
- if (!response.ok) {
134
- const text = await response.text().catch(() => '');
135
- throw new Error(`Tool execution failed (${response.status}): ${text}`);
218
+ async callToolResult(toolName, args) {
219
+ const answer = await this.rpc(`tools/call ${toolName}`, 'tools/call', { name: toolName, arguments: args }, this.toolTimeoutMs);
220
+ if (!answer.ok) {
221
+ throw new Error(`Tool execution failed (${answer.status}): ${answer.text}`);
136
222
  }
137
- const data = await response.json();
223
+ const data = answer.body ?? {};
138
224
  if (data.error) {
139
225
  throw new Error(`Tool error: ${data.error.message}`);
140
226
  }
141
- // Extract text content from MCP response
142
- const content = data.result?.content;
143
- if (Array.isArray(content) && content.length > 0) {
144
- const textContent = content.find((c) => c.type === 'text');
145
- if (textContent?.text) {
146
- try {
147
- return JSON.parse(textContent.text);
148
- }
149
- catch {
150
- return textContent.text;
151
- }
227
+ const result = data.result ?? {};
228
+ return {
229
+ content: Array.isArray(result.content) ? result.content : [],
230
+ ...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),
231
+ ...(typeof result.isError === 'boolean' ? { isError: result.isError } : {}),
232
+ };
233
+ }
234
+ /**
235
+ * Execute a tool call and return what the model should read: the first
236
+ * text block (parsed when it is JSON), else the whole result.
237
+ */
238
+ async callTool(toolName, args) {
239
+ const result = await this.callToolResult(toolName, args);
240
+ const textContent = result.content.find((c) => c?.type === 'text');
241
+ if (textContent?.text) {
242
+ try {
243
+ return JSON.parse(textContent.text);
244
+ }
245
+ catch {
246
+ return textContent.text;
152
247
  }
153
248
  }
154
- return data.result;
249
+ return result;
155
250
  }
156
251
  // ── Management API ──────────────────────────────────────────────
157
252
  // These let LLMs control the almyty platform itself — create APIs,
@@ -199,7 +294,8 @@ export class AlmytyProxy {
199
294
  async importSchema(apiId, data) { return this.rest('POST', `/apis/${apiId}/import-schema`, data); }
200
295
  async generateTools(apiId) { return this.rest('POST', `/apis/${apiId}/generate-tools`); }
201
296
  async listTools() { return this.rest('GET', '/tools'); }
202
- async listGateways() { return this.rest('GET', '/gateways'); }
297
+ // Gateways are MCP, UTCP and Skills; an agent's channels are not listed.
298
+ async listGateways() { return this.rest('GET', '/gateways?kind=tool'); }
203
299
  async createGateway(data) { return this.rest('POST', '/gateways', data); }
204
300
  async assignToolToGateway(gatewayId, toolId) { return this.rest('POST', `/gateways/${gatewayId}/tools`, { toolId }); }
205
301
  async listAgents() { return this.rest('GET', '/agents'); }
@@ -0,0 +1,29 @@
1
+ import type { McpToolDefinition, UpstreamToolResult } from './proxy.js';
2
+ type SchemaFactory = (schema: any) => unknown;
3
+ /** The tool annotations MCP defines, each kept only with the type it must have. */
4
+ export declare function cleanAnnotations(value: unknown): Record<string, unknown> | undefined;
5
+ /** Icons with an https (or data:) source; anything else is left out. */
6
+ export declare function cleanIcons(value: unknown): Array<Record<string, unknown>> | undefined;
7
+ export interface GatewayToolConfig {
8
+ title?: string;
9
+ description: string;
10
+ inputSchema: unknown;
11
+ outputSchema?: unknown;
12
+ annotations?: Record<string, unknown>;
13
+ icons?: Array<Record<string, unknown>>;
14
+ }
15
+ /**
16
+ * The registration config for one gateway tool. Throws when the gateway's
17
+ * schema is not valid JSON Schema; the caller skips that tool and says why.
18
+ */
19
+ export declare function gatewayToolConfig(tool: McpToolDefinition, fromJson?: SchemaFactory): GatewayToolConfig;
20
+ /**
21
+ * The result a full-mode tool hands back: the gateway's own, so structured
22
+ * content reaches the client next to the text, as its output schema says.
23
+ */
24
+ export declare function passThroughResult(result: UpstreamToolResult): {
25
+ isError?: true | undefined;
26
+ structuredContent?: {} | null | undefined;
27
+ content: any[];
28
+ };
29
+ export {};
@@ -0,0 +1,83 @@
1
+ /**
2
+ * A gateway tool as this server registers it in full mode: everything the
3
+ * gateway says about the tool, not only its parameters.
4
+ *
5
+ * The 1.x SDK wanted a Zod shape, so the JSON Schema a gateway returns was
6
+ * rebuilt as one (top-level properties only), and the tool's title, output
7
+ * schema and annotations were dropped on the way. The 2.x SDK takes the JSON
8
+ * Schema itself (`fromJsonSchema`), so the registration now carries:
9
+ *
10
+ * - `inputSchema`: the gateway's schema, unchanged (nested objects, enums,
11
+ * formats and `x-mcp-header` included);
12
+ * - `outputSchema`: when the gateway declares an object-shaped one, so a
13
+ * client gets the structured result it promises;
14
+ * - `title`, `annotations` (read-only, destructive, idempotent, open-world
15
+ * hints) and `icons`, as the gateway lists them.
16
+ *
17
+ * A tool whose schema is not valid JSON Schema is not registered: it could
18
+ * not be called correctly, and the SDK would refuse it anyway.
19
+ */
20
+ import { fromJsonSchema } from '@modelcontextprotocol/server';
21
+ const HINTS = ['readOnlyHint', 'destructiveHint', 'idempotentHint', 'openWorldHint'];
22
+ function isPlainObject(value) {
23
+ return !!value && typeof value === 'object' && !Array.isArray(value);
24
+ }
25
+ /** An object-typed JSON Schema, which is all MCP allows for a tool's input and output. */
26
+ function isObjectSchema(value) {
27
+ if (!isPlainObject(value))
28
+ return false;
29
+ return value.type === undefined || value.type === 'object';
30
+ }
31
+ /** The tool annotations MCP defines, each kept only with the type it must have. */
32
+ export function cleanAnnotations(value) {
33
+ if (!isPlainObject(value))
34
+ return undefined;
35
+ const out = {};
36
+ for (const hint of HINTS) {
37
+ if (typeof value[hint] === 'boolean')
38
+ out[hint] = value[hint];
39
+ }
40
+ if (typeof value.title === 'string' && value.title)
41
+ out.title = value.title;
42
+ return Object.keys(out).length ? out : undefined;
43
+ }
44
+ /** Icons with an https (or data:) source; anything else is left out. */
45
+ export function cleanIcons(value) {
46
+ if (!Array.isArray(value))
47
+ return undefined;
48
+ const icons = value.filter((icon) => isPlainObject(icon) && typeof icon.src === 'string' && /^(https:|data:)/.test(icon.src));
49
+ return icons.length ? icons : undefined;
50
+ }
51
+ /**
52
+ * The registration config for one gateway tool. Throws when the gateway's
53
+ * schema is not valid JSON Schema; the caller skips that tool and says why.
54
+ */
55
+ export function gatewayToolConfig(tool, fromJson = fromJsonSchema) {
56
+ const input = isObjectSchema(tool.inputSchema) ? tool.inputSchema : { type: 'object', properties: {} };
57
+ const config = {
58
+ description: tool.description || `Tool: ${tool.name}`,
59
+ inputSchema: fromJson({ type: 'object', ...input }),
60
+ };
61
+ if (typeof tool.title === 'string' && tool.title)
62
+ config.title = tool.title;
63
+ if (isObjectSchema(tool.outputSchema))
64
+ config.outputSchema = fromJson({ type: 'object', ...tool.outputSchema });
65
+ const annotations = cleanAnnotations(tool.annotations);
66
+ if (annotations)
67
+ config.annotations = annotations;
68
+ const icons = cleanIcons(tool.icons);
69
+ if (icons)
70
+ config.icons = icons;
71
+ return config;
72
+ }
73
+ /**
74
+ * The result a full-mode tool hands back: the gateway's own, so structured
75
+ * content reaches the client next to the text, as its output schema says.
76
+ */
77
+ export function passThroughResult(result) {
78
+ return {
79
+ content: result.content,
80
+ ...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),
81
+ ...(result.isError ? { isError: true } : {}),
82
+ };
83
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@almyty/mcp-server",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -36,9 +36,9 @@
36
36
  "author": "almyty",
37
37
  "license": "Apache-2.0",
38
38
  "dependencies": {
39
- "@almyty/client": "^1.5.0",
40
- "@modelcontextprotocol/sdk": "^1.7.0",
41
- "zod": "^3.22.0"
39
+ "@almyty/client": "^1.5.2",
40
+ "@modelcontextprotocol/server": "^2.2.0",
41
+ "zod": "^4.6.5"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^25.5.0",
package/dist/schema.d.ts DELETED
@@ -1,36 +0,0 @@
1
- /**
2
- * A gateway tool arrives with a JSON Schema; the MCP SDK's `tool()` wants a
3
- * Zod raw shape, one Zod type per top-level property. Handing it the JSON
4
- * Schema object itself meant its values were a string and a nested object
5
- * rather than Zod types, so full mode registered tools whose parameters the
6
- * SDK could not describe.
7
- *
8
- * The Zod namespace is a parameter rather than an import so the mapping can
9
- * be checked on its own.
10
- */
11
- export interface ZodLike {
12
- string(): any;
13
- number(): any;
14
- boolean(): any;
15
- array(inner: any): any;
16
- record(inner: any): any;
17
- unknown(): any;
18
- enum(values: [string, ...string[]]): any;
19
- }
20
- interface JsonSchemaNode {
21
- type?: string | string[];
22
- description?: string;
23
- enum?: unknown[];
24
- items?: JsonSchemaNode;
25
- properties?: Record<string, JsonSchemaNode>;
26
- required?: string[];
27
- }
28
- /** One JSON Schema node to one Zod type. Anything unrecognised stays unknown. */
29
- export declare function zodTypeFor(node: JsonSchemaNode | undefined, z: ZodLike): any;
30
- /**
31
- * The top level of a tool's JSON Schema as a Zod raw shape. Properties not
32
- * listed in `required` are optional, and a schema with no properties is an
33
- * empty shape, which is how the SDK spells "this tool takes no arguments".
34
- */
35
- export declare function buildZodShape(schema: unknown, z: ZodLike): Record<string, any>;
36
- export {};
package/dist/schema.js DELETED
@@ -1,52 +0,0 @@
1
- /**
2
- * A gateway tool arrives with a JSON Schema; the MCP SDK's `tool()` wants a
3
- * Zod raw shape, one Zod type per top-level property. Handing it the JSON
4
- * Schema object itself meant its values were a string and a nested object
5
- * rather than Zod types, so full mode registered tools whose parameters the
6
- * SDK could not describe.
7
- *
8
- * The Zod namespace is a parameter rather than an import so the mapping can
9
- * be checked on its own.
10
- */
11
- /** One JSON Schema node to one Zod type. Anything unrecognised stays unknown. */
12
- export function zodTypeFor(node, z) {
13
- if (!node)
14
- return z.unknown();
15
- // A string enum is the one case worth narrowing: it is how a tool says
16
- // "one of these", and the model behaves better when told.
17
- if (Array.isArray(node.enum) && node.enum.length > 0 && node.enum.every((v) => typeof v === 'string')) {
18
- return z.enum(node.enum);
19
- }
20
- // A union type (["string","null"]) is taken by its first concrete member;
21
- // optionality is carried separately, by `required`.
22
- const type = Array.isArray(node.type) ? node.type.find((t) => t !== 'null') : node.type;
23
- switch (type) {
24
- case 'string': return z.string();
25
- case 'number': return z.number();
26
- case 'integer': return z.number();
27
- case 'boolean': return z.boolean();
28
- case 'array': return z.array(zodTypeFor(node.items, z));
29
- case 'object': return z.record(z.unknown());
30
- default: return z.unknown();
31
- }
32
- }
33
- /**
34
- * The top level of a tool's JSON Schema as a Zod raw shape. Properties not
35
- * listed in `required` are optional, and a schema with no properties is an
36
- * empty shape, which is how the SDK spells "this tool takes no arguments".
37
- */
38
- export function buildZodShape(schema, z) {
39
- const node = (schema ?? {});
40
- const properties = node.properties ?? {};
41
- const required = new Set(node.required ?? []);
42
- const shape = {};
43
- for (const [key, definition] of Object.entries(properties)) {
44
- let field = zodTypeFor(definition, z);
45
- if (definition?.description && typeof field?.describe === 'function')
46
- field = field.describe(definition.description);
47
- if (!required.has(key) && typeof field?.optional === 'function')
48
- field = field.optional();
49
- shape[key] = field;
50
- }
51
- return shape;
52
- }