@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/index.js CHANGED
@@ -11,25 +11,38 @@
11
11
  * The model reads a skill to learn a workflow, then calls almyty_execute with
12
12
  * a tool name and parameters.
13
13
  *
14
- * Two rules this file lives by:
14
+ * Rules this file lives by:
15
15
  *
16
16
  * **stdout is the protocol.** Every diagnostic goes to stderr; one stray
17
17
  * console.log on stdout corrupts the JSON-RPC stream and the host editor
18
18
  * loses the server with no useful error.
19
19
  *
20
- * **The transport connects before anything is fetched.** Discovery used to
21
- * run first, so a backend that was down or a stale token killed the process
22
- * during the handshake. Now the handshake always succeeds and a discovery
23
- * failure is reported on the tool call that needed it.
20
+ * **The handshake never waits for the backend.** Discovery runs in the
21
+ * background, so a backend that is down or a stale token cannot kill the
22
+ * process during the handshake; a discovery failure is reported on the tool
23
+ * call that needed it.
24
+ *
25
+ * **Both protocol eras, from one factory.** `serveStdio` (MCP SDK 2.x) lets
26
+ * the client's first message decide: an `initialize` (MCP 2024-11-05 ..
27
+ * 2025-11-25, what Claude Desktop, Cursor and most editors send today) pins
28
+ * the connection to the earlier protocol; a request carrying `_meta` pins it
29
+ * to MCP 2026-07-28. `buildServer` registers the same tools either way.
30
+ *
31
+ * **No notifications before the client is ready (#875).** What discovery
32
+ * found is registered late, and every late registration makes the SDK send
33
+ * a list_changed notification. On the earlier protocol that is held until
34
+ * the client has sent `notifications/initialized`, as the MCP lifecycle
35
+ * requires. On 2026-07-28 there is no handshake and the SDK sends
36
+ * notifications only on a `subscriptions/listen` stream the client opened.
24
37
  */
25
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
26
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
38
+ import { McpServer } from '@modelcontextprotocol/server';
39
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
27
40
  import { z } from 'zod';
28
41
  import { resolveCredentials } from './auth.js';
29
- import { AlmytyProxy } from './proxy.js';
42
+ import { AlmytyProxy, upstreamEraFromEnv } from './proxy.js';
30
43
  import { ToolCatalog, searchResultText, uniquePromptNames, upstreamErrorText } from './catalog.js';
31
44
  import { EXIT, EXIT_CODE_HELP, exitCodeFor } from './exit-codes.js';
32
- import { buildZodShape } from './schema.js';
45
+ import { gatewayToolConfig, passThroughResult } from './registration.js';
33
46
  import { VERSION } from './version.js';
34
47
  // Accept gateway as positional arg or env var:
35
48
  // npx @almyty/mcp-server acme/petstore
@@ -55,91 +68,54 @@ function textResult(result) {
55
68
  }],
56
69
  };
57
70
  }
58
- async function main() {
59
- // Resolve token: env var > ~/.almyty/credentials.json
60
- const creds = resolveCredentials();
61
- if (!creds) {
62
- log('no authentication token found.\n' +
63
- ' Set ALMYTY_TOKEN, or run: npx @almyty/auth login');
64
- process.exit(EXIT.AUTH);
65
- }
66
- const ALMYTY_URL = creds.url;
67
- const proxy = new AlmytyProxy(ALMYTY_URL, creds.token, ALMYTY_GATEWAY_ID);
68
- const catalog = new ToolCatalog(proxy, { warn: (m) => log(m) });
69
- const server = new McpServer({ name: 'almyty', version: VERSION });
70
- // ── Gateway tools ────────────────────────────────────────────────
71
- if (ALMYTY_MODE === 'skill-first') {
72
- // Two tools instead of N: ~300 tokens of context rather than N * ~200.
73
- // Neither depends on discovery having finished, which is what lets the
74
- // handshake complete before the first network call.
75
- server.tool('almyty_execute', 'Execute any almyty API tool by name. Read the relevant skill prompt first to understand which tool to use and what parameters are needed, or call almyty_search to find one.', {
76
- tool_name: z.string().describe('Name of the almyty tool to execute (from skill instructions or almyty_search)'),
77
- parameters: z.record(z.unknown()).describe('Parameters for the tool (see the skill for required params)'),
78
- }, async (args) => {
79
- try {
80
- return textResult(await proxy.callTool(args.tool_name, args.parameters));
81
- }
82
- catch (error) {
83
- return errorResult(error);
84
- }
85
- });
86
- server.tool('almyty_search', 'Search the available API tools by keyword. Returns matching tool names and descriptions. Use this to discover which tools exist before calling almyty_execute.', {
87
- query: z.string().describe('Search query (e.g. "create pet", "list users", "payment"). Empty lists everything.'),
88
- }, async (args) => {
89
- // The gateway's tool list changes while the editor is open, so the
90
- // index is re-asked when it has gone stale instead of being a
91
- // snapshot from whenever the editor last started.
92
- await catalog.ensureFresh();
93
- if (!catalog.discovered && catalog.lastError) {
94
- return errorResult(new Error(catalog.lastError));
95
- }
96
- return textResult(searchResultText(args.query, catalog.search(args.query), catalog.tools));
97
- });
98
- }
99
- // ── Management tools — control almyty itself ─────────────────────
100
- // Registered in both modes: create APIs, import schemas, wire gateways,
101
- // build and invoke agents. None of them needs discovery either.
102
- const management = [
71
+ /** ALMYTY_DISCOVERY_WAIT_MS: how long the first client message waits for discovery (0 to 60000, default 5000). */
72
+ function discoveryWaitMs(value = process.env.ALMYTY_DISCOVERY_WAIT_MS) {
73
+ const n = value === undefined || value.trim() === '' ? NaN : Number(value);
74
+ return Number.isInteger(n) && n >= 0 && n <= 60_000 ? n : 5_000;
75
+ }
76
+ /** The management tools: control almyty itself. Registered in both modes; none needs discovery. */
77
+ function managementTools(proxy) {
78
+ return [
103
79
  {
104
80
  name: 'almyty_list_apis',
105
81
  description: 'List all connected APIs in your organization.',
106
- shape: {},
82
+ input: z.object({}),
107
83
  run: () => proxy.listApis(),
108
84
  },
109
85
  {
110
86
  name: 'almyty_create_api',
111
87
  description: 'Connect a new API. Provide a name, type (openapi/graphql/soap/protobuf/sdk), and base URL.',
112
- shape: {
88
+ input: z.object({
113
89
  name: z.string().describe('Human-readable API name'),
114
90
  type: z.enum(['openapi', 'graphql', 'soap', 'protobuf', 'sdk']).describe('Schema type'),
115
91
  baseUrl: z.string().optional().describe('API base URL (not needed for SDK type)'),
116
- },
92
+ }),
117
93
  run: (args) => proxy.createApi(args),
118
94
  },
119
95
  {
120
96
  name: 'almyty_import_schema',
121
97
  description: 'Import an API schema and auto-generate tools. Provide the API ID and a schema URL.',
122
- shape: {
98
+ input: z.object({
123
99
  apiId: z.string().describe('ID of the API to import into'),
124
100
  schemaUrl: z.string().describe('URL of the schema (e.g. an OpenAPI JSON endpoint)'),
125
101
  generateTools: z.boolean().default(true).describe('Auto-generate tools from operations'),
126
- },
102
+ }),
127
103
  run: (args) => proxy.importSchema(args.apiId, { schemaUrl: args.schemaUrl, generateTools: args.generateTools }),
128
104
  },
129
105
  {
130
106
  name: 'almyty_list_gateways',
131
- description: 'List all gateways in your organization.',
132
- shape: {},
107
+ description: 'List the gateways in your organization: MCP, UTCP and Skills gateways serving tools. An agent\'s channels (web chat, messaging, A2A) are not gateways.',
108
+ input: z.object({}),
133
109
  run: () => proxy.listGateways(),
134
110
  },
135
111
  {
136
112
  name: 'almyty_create_gateway',
137
113
  description: 'Share tools over one protocol: MCP, UTCP or Skills (one gateway each). An agent is put in front of people or other agents (web, chat apps, A2A) through an app, not here.',
138
- shape: {
114
+ input: z.object({
139
115
  name: z.string().describe('Gateway name'),
140
116
  type: z.enum(['mcp', 'utcp', 'skills']).default('mcp').describe('The one protocol this gateway serves'),
141
117
  endpoint: z.string().describe('URL slug for the gateway endpoint'),
142
- },
118
+ }),
143
119
  run: (args) => proxy.createGateway({
144
120
  ...args,
145
121
  kind: 'tool',
@@ -149,58 +125,108 @@ async function main() {
149
125
  {
150
126
  name: 'almyty_assign_tool',
151
127
  description: 'Assign a tool to a tool-kind gateway.',
152
- shape: {
128
+ input: z.object({
153
129
  gatewayId: z.string().describe('Gateway ID'),
154
130
  toolId: z.string().describe('Tool ID to assign'),
155
- },
131
+ }),
156
132
  run: (args) => proxy.assignToolToGateway(args.gatewayId, args.toolId),
157
133
  },
158
134
  {
159
135
  name: 'almyty_list_agents',
160
136
  description: 'List all agents in your organization.',
161
- shape: {},
137
+ input: z.object({}),
162
138
  run: () => proxy.listAgents(),
163
139
  },
164
140
  {
165
141
  name: 'almyty_create_agent',
166
142
  description: 'Create an agent. Workflow agents run a visual DAG pipeline; autonomous agents run from instructions plus tool access.',
167
- shape: {
143
+ input: z.object({
168
144
  name: z.string().describe('Agent name'),
169
145
  description: z.string().optional().describe('What the agent does'),
170
146
  mode: z.enum(['workflow', 'autonomous']).default('autonomous').describe('workflow = visual pipeline, autonomous = instruction-driven'),
171
147
  instructions: z.string().optional().describe('Instructions for autonomous agents'),
172
- },
148
+ }),
173
149
  run: (args) => proxy.createAgent(args),
174
150
  },
175
151
  {
176
152
  name: 'almyty_invoke_agent',
177
153
  description: 'Invoke an agent with input. Returns the agent execution result.',
178
- shape: {
154
+ input: z.object({
179
155
  agentId: z.string().describe('Agent ID'),
180
- input: z.record(z.unknown()).describe('Input data for the agent'),
181
- },
156
+ input: z.record(z.string(), z.unknown()).describe('Input data for the agent'),
157
+ }),
182
158
  run: (args) => proxy.invokeAgent(args.agentId, args.input),
183
159
  },
184
160
  {
185
161
  name: 'almyty_list_providers',
186
162
  description: 'List the LLM providers configured in your organization, with the credential backing each one.',
187
- shape: {},
163
+ input: z.object({}),
188
164
  run: () => proxy.listProviders(),
189
165
  },
190
166
  {
191
167
  name: 'almyty_add_provider',
192
168
  description: 'Add an LLM provider backed by an existing credential. Add the vendor key first with `npx @almyty/credentials add <vendor>` and pass the credential id here. ' +
193
169
  'This tool deliberately does not take an API key: a key passed as a tool argument would be written into this conversation\'s transcript and the host editor\'s logs.',
194
- shape: {
170
+ input: z.object({
195
171
  name: z.string().describe('Display name for the provider'),
196
172
  type: z.string().describe('Provider type (openai, anthropic, gemini, azure, bedrock, ...)'),
197
173
  credentialId: z.string().describe('Id of an existing credential, from `npx @almyty/credentials list`'),
198
- },
174
+ }),
199
175
  run: (args) => proxy.addProvider({ name: args.name, type: args.type, credentialId: args.credentialId, configuration: {} }),
200
176
  },
201
177
  ];
178
+ }
179
+ /**
180
+ * One MCP server instance, for one connection in one era. Everything that
181
+ * does not depend on discovery is registered here, before the instance is
182
+ * handed to the SDK; what discovery found is registered once the client is
183
+ * ready (see the file comment).
184
+ */
185
+ function buildServer(era, deps, discoveredAlready) {
186
+ const { proxy, catalog, discovered, url } = deps;
187
+ const server = new McpServer({ name: 'almyty', version: VERSION });
188
+ // ── Gateway tools ────────────────────────────────────────────────
189
+ if (ALMYTY_MODE === 'skill-first') {
190
+ // Two tools instead of N: ~300 tokens of context rather than N * ~200.
191
+ // Neither depends on discovery having finished, which is what lets the
192
+ // handshake complete before the first network call.
193
+ server.registerTool('almyty_execute', {
194
+ description: 'Execute any almyty API tool by name. Read the relevant skill prompt first to understand which tool to use and what parameters are needed, or call almyty_search to find one.',
195
+ inputSchema: z.object({
196
+ tool_name: z.string().describe('Name of the almyty tool to execute (from skill instructions or almyty_search)'),
197
+ parameters: z.record(z.string(), z.unknown()).describe('Parameters for the tool (see the skill for required params)'),
198
+ }),
199
+ }, async (args) => {
200
+ try {
201
+ return textResult(await proxy.callTool(args.tool_name, args.parameters));
202
+ }
203
+ catch (error) {
204
+ return errorResult(error);
205
+ }
206
+ });
207
+ server.registerTool('almyty_search', {
208
+ description: 'Search the available API tools by keyword. Returns matching tool names and descriptions. Use this to discover which tools exist before calling almyty_execute.',
209
+ inputSchema: z.object({
210
+ query: z.string().describe('Search query (e.g. "create pet", "list users", "payment"). Empty lists everything.'),
211
+ }),
212
+ annotations: { readOnlyHint: true, openWorldHint: false },
213
+ }, async (args) => {
214
+ // The gateway's tool list changes while the editor is open, so the
215
+ // index is re-asked when it has gone stale instead of being a
216
+ // snapshot from whenever the editor last started.
217
+ await catalog.ensureFresh();
218
+ if (!catalog.discovered && catalog.lastError) {
219
+ return errorResult(new Error(catalog.lastError));
220
+ }
221
+ return textResult(searchResultText(args.query, catalog.search(args.query), catalog.tools));
222
+ });
223
+ }
224
+ // ── Management tools — control almyty itself ─────────────────────
225
+ // Registered in both modes: create APIs, import schemas, wire gateways,
226
+ // build and invoke agents. None of them needs discovery either.
227
+ const management = managementTools(proxy);
202
228
  for (const tool of management) {
203
- server.tool(tool.name, tool.description, tool.shape, async (args) => {
229
+ server.registerTool(tool.name, { description: tool.description, inputSchema: tool.input }, async (args) => {
204
230
  try {
205
231
  return textResult(await tool.run(args));
206
232
  }
@@ -210,15 +236,16 @@ async function main() {
210
236
  });
211
237
  }
212
238
  // Server info, answered from whatever discovery has managed so far.
213
- server.resource('almyty-info', 'almyty://info', async (uri) => ({
239
+ server.registerResource('almyty-info', 'almyty://info', { description: 'This server: the almyty backend, gateway, mode and what discovery found', mimeType: 'application/json' }, async (uri) => ({
214
240
  contents: [{
215
241
  uri: uri.href,
216
242
  mimeType: 'application/json',
217
243
  text: JSON.stringify({
218
- server: ALMYTY_URL,
244
+ server: url,
219
245
  version: VERSION,
220
246
  gatewayId: ALMYTY_GATEWAY_ID || 'all',
221
247
  mode: ALMYTY_MODE,
248
+ protocol: { client: era, upstream: proxy.upstreamEra },
222
249
  discovered: catalog.discovered,
223
250
  tools: catalog.tools.length,
224
251
  skills: catalog.skills.length,
@@ -227,18 +254,15 @@ async function main() {
227
254
  }],
228
255
  }));
229
256
  // A compact index of everything available, as one prompt. Registered
230
- // before connect: the SDK declares the prompts capability on the first
231
- // prompt and refuses to after the transport is up, so a first prompt
232
- // added after discovery killed the server with "Cannot register
233
- // capabilities after connecting to transport". Its description gets
234
- // the tool count once discovery has run.
257
+ // with the instance: its description gets the tool count once discovery
258
+ // has run.
235
259
  let promptNames = [];
236
- const overview = server.prompt('almyty-overview', 'Overview: the API tools available via almyty', async () => {
260
+ const overview = server.registerPrompt('almyty-overview', { description: 'Overview: the API tools available via almyty' }, async () => {
237
261
  await catalog.ensureFresh();
238
262
  const lines = [
239
263
  '# almyty API tools',
240
264
  '',
241
- `Connected to: ${ALMYTY_URL}`,
265
+ `Connected to: ${url}`,
242
266
  ALMYTY_GATEWAY_ID ? `Gateway: ${ALMYTY_GATEWAY_ID}` : 'Gateway: all',
243
267
  '',
244
268
  ];
@@ -252,64 +276,113 @@ async function main() {
252
276
  lines.push('## How to use', '', '1. Load a skill prompt to understand the workflow', '2. Call `almyty_execute` with `tool_name` and `parameters`', '3. Or use `almyty_search` to find the right tool first', '');
253
277
  return { messages: [{ role: 'user', content: { type: 'text', text: lines.filter(Boolean).join('\n') } }] };
254
278
  });
255
- // ── Connect, then discover ───────────────────────────────────────
256
- // This order is the point: the client gets its handshake even when the
257
- // backend is unreachable, so the editor shows a server that explains the
258
- // problem instead of one that died.
259
- const transport = new StdioServerTransport();
260
- await server.connect(transport);
261
- log(`ready on stdio (mode: ${ALMYTY_MODE}, ${management.length} management tools)`);
262
- await catalog.refresh();
263
- if (catalog.lastError) {
264
- log(`gateway discovery failed: ${catalog.lastError}`);
265
- log('the management tools still work; almyty_execute will report this until discovery succeeds');
266
- }
267
- else {
268
- log(`${catalog.tools.length} gateway tools, ${catalog.skills.length} skills`);
269
- }
270
- // Skills as prompts, loaded on demand rather than held in context.
271
- promptNames = uniquePromptNames(catalog.skills.map((s) => s.name));
272
- overview.update({ description: `Overview: ${catalog.tools.length} API tools available via almyty` });
273
- catalog.skills.forEach((skill, i) => {
274
- server.prompt(promptNames[i], `How to use: ${skill.name} (${skill.toolCount} tools)`, async () => ({
275
- messages: [{ role: 'user', content: { type: 'text', text: skill.content } }],
276
- }));
277
- });
278
- if (ALMYTY_MODE === 'full') {
279
- // Every gateway tool individually. The JSON Schema the gateway returns
280
- // is converted to the Zod shape the SDK wants; handing it the raw
281
- // schema left the SDK with no usable parameter types.
282
- for (const tool of catalog.tools) {
283
- server.tool(tool.name, tool.description || `Tool: ${tool.name}`, buildZodShape(tool.inputSchema, z), async (args) => {
279
+ // ── What discovery found ─────────────────────────────────────────
280
+ const registerDiscovered = () => {
281
+ promptNames = uniquePromptNames(catalog.skills.map((s) => s.name));
282
+ overview.update({ description: `Overview: ${catalog.tools.length} API tools available via almyty` });
283
+ catalog.skills.forEach((skill, i) => {
284
+ server.registerPrompt(promptNames[i], { description: `How to use: ${skill.name} (${skill.toolCount} tools)` }, async () => ({
285
+ messages: [{ role: 'user', content: { type: 'text', text: skill.content } }],
286
+ }));
287
+ });
288
+ if (ALMYTY_MODE === 'full') {
289
+ // Every gateway tool individually, as the gateway describes it:
290
+ // its JSON Schema, title, output schema and annotations.
291
+ for (const tool of catalog.tools) {
292
+ let config;
284
293
  try {
285
- return textResult(await proxy.callTool(tool.name, args));
294
+ config = gatewayToolConfig(tool);
286
295
  }
287
296
  catch (error) {
288
- return errorResult(error);
297
+ log(`skipping gateway tool ${tool.name}: its schema is not valid JSON Schema (${error.message})`);
298
+ continue;
289
299
  }
290
- });
300
+ server.registerTool(tool.name, config, async (args) => {
301
+ try {
302
+ return passThroughResult(await proxy.callToolResult(tool.name, args));
303
+ }
304
+ catch (error) {
305
+ return errorResult(error);
306
+ }
307
+ });
308
+ }
291
309
  }
310
+ };
311
+ // Discovery that finished before the client's first message (the factory
312
+ // waits for it a little, see main): register it now, before the instance
313
+ // is connected. Nothing is announced, and the client's first tools/list
314
+ // already has the gateway tools, which matters to clients that list once
315
+ // and never again (Claude Code's `-p` mode, for one).
316
+ if (discoveredAlready) {
317
+ registerDiscovered();
318
+ return server;
292
319
  }
293
- // Registrations happened after the handshake, so tell the client its
294
- // lists changed. A client that does not care ignores it.
295
- // Feature-detected rather than called outright: these notifications are
296
- // a courtesy, and nothing here depends on one arriving or on a particular
297
- // SDK version carrying them.
298
- const lowLevel = server.server;
299
- const notify = (method) => {
300
- const fn = lowLevel?.[method];
301
- if (typeof fn !== 'function')
302
- return;
303
- try {
304
- fn.call(lowLevel);
320
+ // Otherwise once discovery has run and the client is ready. On the
321
+ // earlier protocol the client is ready once it has sent
322
+ // `notifications/initialized`: the lifecycle forbids notifications before
323
+ // that, and a discovery that failed fast used to announce its prompts
324
+ // before the client had even sent `initialize` (#875). On 2026-07-28 there
325
+ // is no handshake; the SDK announces late registrations only on a
326
+ // `subscriptions/listen` stream. Every late registration makes the SDK
327
+ // announce the change, so the client re-reads its lists.
328
+ const clientReady = era === 'legacy'
329
+ ? new Promise((resolve) => {
330
+ const lowLevel = server.server;
331
+ const previous = lowLevel.oninitialized;
332
+ lowLevel.oninitialized = () => {
333
+ previous?.();
334
+ resolve();
335
+ };
336
+ })
337
+ : Promise.resolve();
338
+ void Promise.all([discovered, clientReady])
339
+ .then(registerDiscovered)
340
+ .catch((error) => log(`could not register what discovery found: ${upstreamErrorText(error)}`));
341
+ return server;
342
+ }
343
+ async function main() {
344
+ // Resolve token: env var > ~/.almyty/credentials.json
345
+ const creds = resolveCredentials();
346
+ if (!creds) {
347
+ log('no authentication token found.\n' +
348
+ ' Set ALMYTY_TOKEN, or run: npx @almyty/auth login');
349
+ process.exit(EXIT.AUTH);
350
+ }
351
+ const ALMYTY_URL = creds.url;
352
+ const proxy = new AlmytyProxy(ALMYTY_URL, creds.token, ALMYTY_GATEWAY_ID, {
353
+ era: upstreamEraFromEnv(),
354
+ clientVersion: VERSION,
355
+ });
356
+ const catalog = new ToolCatalog(proxy, { warn: (m) => log(m) });
357
+ // Discovery starts at once, alongside the transport. It never throws; the
358
+ // instance a client connects to registers what it found when both are
359
+ // ready.
360
+ const discovered = catalog.refresh().then(() => {
361
+ if (catalog.lastError) {
362
+ log(`gateway discovery failed: ${catalog.lastError}`);
363
+ log('the management tools still work; almyty_execute will report this until discovery succeeds');
305
364
  }
306
- catch {
307
- // A client that refuses the notification changes nothing.
365
+ else {
366
+ log(`${catalog.tools.length} gateway tools, ${catalog.skills.length} skills (upstream: MCP ${proxy.upstreamEra === 'modern' ? '2026-07-28' : '2025'})`);
308
367
  }
309
- };
310
- if (ALMYTY_MODE === 'full' && catalog.tools.length > 0)
311
- notify('sendToolListChanged');
312
- notify('sendPromptListChanged');
368
+ });
369
+ // The client's first message calls the factory. Discovery has usually
370
+ // finished by then; if not, it is waited for up to ALMYTY_DISCOVERY_WAIT_MS
371
+ // so the first tools/list is complete, and past that the handshake goes
372
+ // ahead without it (a backend that does not answer must not hold the
373
+ // client) and what discovery finds is registered late.
374
+ const waitMs = discoveryWaitMs();
375
+ let settled = false;
376
+ void discovered.then(() => { settled = true; });
377
+ serveStdio(async (ctx) => {
378
+ if (!settled && waitMs > 0) {
379
+ await Promise.race([discovered, new Promise((resolve) => setTimeout(resolve, waitMs).unref())]);
380
+ }
381
+ return buildServer(ctx.era, { proxy, catalog, discovered, url: ALMYTY_URL }, settled);
382
+ }, {
383
+ onerror: (error) => log(`protocol error: ${error.message}`),
384
+ });
385
+ log(`ready on stdio (mode: ${ALMYTY_MODE}, ${managementTools(proxy).length} management tools)`);
313
386
  }
314
387
  function printHelp() {
315
388
  console.log(`
@@ -330,7 +403,8 @@ Usage:
330
403
 
331
404
  The server speaks MCP over stdio: stdout carries the protocol and every
332
405
  diagnostic goes to stderr. It is meant to be launched by an MCP client, not
333
- run by hand.
406
+ run by hand. It speaks MCP 2026-07-28 and the earlier versions (2024-11-05 to
407
+ 2025-11-25) alike: the client's first message decides.
334
408
 
335
409
  Modes (ALMYTY_MODE):
336
410
  skill-first (default) almyty_execute + almyty_search, and skills as prompts.
@@ -358,6 +432,12 @@ Environment:
358
432
  ALMYTY_TOKEN Token (otherwise read from ~/.almyty/credentials.json)
359
433
  ALMYTY_GATEWAY_ID Gateway as "orgSlug/gatewaySlug" (alternative to the positional arg)
360
434
  ALMYTY_MODE "skill-first" (default) | "full"
435
+ ALMYTY_MCP_PROTOCOL How this server talks to almyty: "auto" (default: MCP
436
+ 2026-07-28, falling back to the earlier protocol for an
437
+ older almyty), "modern" or "legacy"
438
+ ALMYTY_DISCOVERY_WAIT_MS How long the client's first message waits for the
439
+ gateway's tool list, so it is complete from the start
440
+ (default 5000; 0 = never wait, announce the tools later)
361
441
 
362
442
  Configuration:
363
443
  Claude Code: claude mcp add petstore -- npx -y @almyty/mcp-server acme/petstore
package/dist/proxy.d.ts CHANGED
@@ -1,18 +1,63 @@
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
  */
5
18
  export interface McpToolDefinition {
6
19
  name: string;
20
+ title?: string;
7
21
  description?: string;
8
22
  inputSchema: Record<string, unknown>;
23
+ outputSchema?: Record<string, unknown>;
24
+ annotations?: Record<string, unknown>;
25
+ icons?: unknown[];
9
26
  }
27
+ /** A tools/call result as the upstream returned it, without the 2026 envelope fields. */
28
+ export interface UpstreamToolResult {
29
+ content: any[];
30
+ structuredContent?: unknown;
31
+ isError?: boolean;
32
+ }
33
+ /** Which protocol era the proxy speaks upstream. */
34
+ export type UpstreamEra = 'auto' | 'modern' | 'legacy';
35
+ export declare const MODERN_PROTOCOL_VERSION = "2026-07-28";
36
+ /** ALMYTY_MCP_PROTOCOL, read leniently: anything unknown is `auto`. */
37
+ export declare function upstreamEraFromEnv(value?: string | undefined): UpstreamEra;
38
+ /**
39
+ * A header value as MCP 2026-07-28 carries it: as is when it is plain
40
+ * printable ASCII with no surrounding whitespace, otherwise the Base64
41
+ * sentinel `=?base64?...?=` of its UTF-8 bytes.
42
+ */
43
+ export declare function encodeMcpHeaderValue(value: string): string;
44
+ /**
45
+ * Whether an answer to a modern request says "this server does not speak
46
+ * 2026-07-28": the 400 a backend from before it gives an unknown
47
+ * MCP-Protocol-Version (-32600 naming the version), or the 2026 code for it
48
+ * (-32022).
49
+ */
50
+ export declare function isEraRefusal(status: number, body: any): boolean;
10
51
  interface ProxyOptions {
11
52
  /** Override for fetch timeouts. */
12
53
  discoveryTimeoutMs?: number;
13
54
  toolTimeoutMs?: number;
14
55
  /** Optional logger for non-fatal warnings (e.g. skills/list failure). */
15
56
  warn?: (msg: string) => void;
57
+ /** Which protocol era to speak upstream (default: auto). */
58
+ era?: UpstreamEra;
59
+ /** This package's version, sent as clientInfo on modern requests. */
60
+ clientVersion?: string;
16
61
  }
17
62
  export declare class AlmytyProxy {
18
63
  private readonly baseUrl;
@@ -21,18 +66,32 @@ export declare class AlmytyProxy {
21
66
  private readonly discoveryTimeoutMs;
22
67
  private readonly toolTimeoutMs;
23
68
  private readonly warn;
69
+ private readonly configuredEra;
70
+ private readonly clientVersion;
71
+ /** The era the upstream turned out to speak; null until a request has told. */
72
+ private resolvedEra;
24
73
  private requestSeq;
25
74
  constructor(baseUrl: string, token: string, gatewayId?: string, options?: ProxyOptions);
75
+ /** The era upstream requests are sent in now. */
76
+ get upstreamEra(): 'modern' | 'legacy';
26
77
  private endpoint;
27
78
  private nextId;
79
+ /** The body and headers of one JSON-RPC request in an era. */
80
+ private request;
28
81
  /**
29
- * Wrap a fetch with an AbortSignal-based timeout. Without this, a hung
82
+ * One POST with an AbortSignal-based timeout. Without this, a hung
30
83
  * backend (e.g., a load-balancer black-hole) would hang the MCP server
31
84
  * indefinitely with no signal to the LLM client.
32
85
  */
33
- private fetchWithTimeout;
86
+ private post;
34
87
  /**
35
- * Fetch available tools from the almyty backend.
88
+ * A JSON-RPC call upstream in the current era, falling back to legacy once
89
+ * when the backend refuses 2026-07-28 (in `auto` mode only).
90
+ */
91
+ private rpc;
92
+ /**
93
+ * Fetch available tools from the almyty backend, with everything the
94
+ * gateway says about each: title, schemas, annotations, icons.
36
95
  */
37
96
  fetchTools(): Promise<McpToolDefinition[]>;
38
97
  /**
@@ -46,7 +105,13 @@ export declare class AlmytyProxy {
46
105
  toolCount: number;
47
106
  }>>;
48
107
  /**
49
- * Execute a tool call via the almyty backend.
108
+ * Execute a tool call via the almyty backend and return its result as
109
+ * the gateway gave it: content blocks, structured content, isError.
110
+ */
111
+ callToolResult(toolName: string, args: Record<string, unknown>): Promise<UpstreamToolResult>;
112
+ /**
113
+ * Execute a tool call and return what the model should read: the first
114
+ * text block (parsed when it is JSON), else the whole result.
50
115
  */
51
116
  callTool(toolName: string, args: Record<string, unknown>): Promise<unknown>;
52
117
  /**