@almyty/mcp-server 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -47,7 +47,9 @@ Set `ALMYTY_MODE`:
47
47
  - **`skill-first`** (default) — the two tools above plus skills as prompts.
48
48
  - **`full`** — every gateway tool registered individually, traditional MCP.
49
49
  Higher context cost. The list is read once at startup, and the client is
50
- notified when it arrives.
50
+ notified when it arrives. Each tool keeps its title, full input schema,
51
+ output schema and annotations as the gateway gives them, and a call returns
52
+ the gateway's structured result next to the text.
51
53
 
52
54
  ## Management tools
53
55
 
@@ -63,13 +65,13 @@ assistant:
63
65
  | `almyty_invoke_agent` | `almyty_list_providers` |
64
66
  | `almyty_add_provider` | |
65
67
 
66
- `almyty_add_provider` takes a **connection id**, never an API key. A key
68
+ `almyty_add_provider` takes a **credential id**, never an API key. A key
67
69
  passed as a tool argument would be written into the assistant's transcript and
68
- the host editor's logs, so the key goes through the connections flow instead:
70
+ the host editor's logs, so the key goes through `@almyty/credentials` instead:
69
71
 
70
72
  ```bash
71
- npx @almyty/connections connect openai
72
- npx @almyty/connections list # -> the id to hand the tool
73
+ npx @almyty/credentials add openai
74
+ npx @almyty/credentials list # -> the id to hand the tool
73
75
  ```
74
76
 
75
77
  ## When almyty is not reachable
@@ -85,6 +87,16 @@ throughout.
85
87
  Every call is bounded: 15 seconds for discovery, 120 for a tool execution.
86
88
  A hung backend fails the call rather than hanging your editor.
87
89
 
90
+ ## MCP versions
91
+
92
+ The server speaks MCP 2026-07-28 and the earlier versions (2024-11-05 to
93
+ 2025-11-25) alike: the client's first message decides. A client that opens with
94
+ `initialize` (Claude Desktop, Cursor and most editors today) gets the earlier
95
+ protocol, and no notification before it has sent `notifications/initialized`.
96
+ A client that opens with a 2026-07-28 request is served statelessly and hears
97
+ about tool and prompt changes only on a `subscriptions/listen` stream it
98
+ opened.
99
+
88
100
  ## stdio discipline
89
101
 
90
102
  stdout carries the MCP protocol and nothing else; every diagnostic goes to
@@ -156,6 +168,8 @@ args = ["-y", "@almyty/mcp-server"]
156
168
  | `ALMYTY_TOKEN` | Token; otherwise read from `~/.almyty/credentials.json` |
157
169
  | `ALMYTY_GATEWAY_ID` | Gateway as `orgSlug/gatewaySlug` (alternative to the positional argument) |
158
170
  | `ALMYTY_MODE` | `skill-first` (default) or `full` |
171
+ | `ALMYTY_MCP_PROTOCOL` | How this server talks to almyty: `auto` (default: MCP 2026-07-28, falling back to the earlier protocol for an older almyty), `modern` or `legacy` |
172
+ | `ALMYTY_DISCOVERY_WAIT_MS` | How long the client's first message waits for the gateway's tool list, so the first list is complete (default 5000; `0` never waits and announces the tools once they arrive) |
159
173
 
160
174
  ## Authentication
161
175
 
package/dist/catalog.js CHANGED
@@ -90,7 +90,7 @@ export function sanitizePromptName(name) {
90
90
  return name
91
91
  .replace(/[^a-zA-Z0-9_-]/g, '_')
92
92
  .replace(/_{2,}/g, '_')
93
- .replace(/^_+|_+$/g, '') || 'skill';
93
+ .replace(/^_+|(?<!_)_+$/g, '') || 'skill';
94
94
  }
95
95
  /**
96
96
  * Prompt names must be unique, and two different skill names can sanitize to
package/dist/index.d.ts CHANGED
@@ -11,15 +11,28 @@
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
38
  export {};
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,150 +68,165 @@ 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
- description: 'Create a gateway that exposes tools OR an agent over a protocol (MCP, A2A, UTCP, Skills). Use kind="tool" for a tool gateway or kind="agent" for an agent gateway.',
138
- shape: {
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.',
114
+ input: z.object({
139
115
  name: z.string().describe('Gateway name'),
140
- type: z.enum(['mcp', 'a2a', 'utcp', 'skills']).describe('Protocol type'),
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
- kind: z.enum(['tool', 'agent']).default('tool').describe('What the gateway exposes: tools or a single agent'),
143
- agentId: z.string().optional().describe('Agent ID (required when kind is "agent")'),
144
- },
145
- run: (args) => proxy.createGateway({ ...args, configuration: {} }),
118
+ }),
119
+ run: (args) => proxy.createGateway({
120
+ ...args,
121
+ kind: 'tool',
122
+ configuration: args.type === 'mcp' ? { transport: 'http' } : args.type === 'utcp' ? { protocol: 'http' } : {},
123
+ }),
146
124
  },
147
125
  {
148
126
  name: 'almyty_assign_tool',
149
127
  description: 'Assign a tool to a tool-kind gateway.',
150
- shape: {
128
+ input: z.object({
151
129
  gatewayId: z.string().describe('Gateway ID'),
152
130
  toolId: z.string().describe('Tool ID to assign'),
153
- },
131
+ }),
154
132
  run: (args) => proxy.assignToolToGateway(args.gatewayId, args.toolId),
155
133
  },
156
134
  {
157
135
  name: 'almyty_list_agents',
158
136
  description: 'List all agents in your organization.',
159
- shape: {},
137
+ input: z.object({}),
160
138
  run: () => proxy.listAgents(),
161
139
  },
162
140
  {
163
141
  name: 'almyty_create_agent',
164
142
  description: 'Create an agent. Workflow agents run a visual DAG pipeline; autonomous agents run from instructions plus tool access.',
165
- shape: {
143
+ input: z.object({
166
144
  name: z.string().describe('Agent name'),
167
145
  description: z.string().optional().describe('What the agent does'),
168
146
  mode: z.enum(['workflow', 'autonomous']).default('autonomous').describe('workflow = visual pipeline, autonomous = instruction-driven'),
169
147
  instructions: z.string().optional().describe('Instructions for autonomous agents'),
170
- },
148
+ }),
171
149
  run: (args) => proxy.createAgent(args),
172
150
  },
173
151
  {
174
152
  name: 'almyty_invoke_agent',
175
153
  description: 'Invoke an agent with input. Returns the agent execution result.',
176
- shape: {
154
+ input: z.object({
177
155
  agentId: z.string().describe('Agent ID'),
178
- input: z.record(z.unknown()).describe('Input data for the agent'),
179
- },
156
+ input: z.record(z.string(), z.unknown()).describe('Input data for the agent'),
157
+ }),
180
158
  run: (args) => proxy.invokeAgent(args.agentId, args.input),
181
159
  },
182
160
  {
183
161
  name: 'almyty_list_providers',
184
- description: 'List the LLM providers configured in your organization, with the connection backing each one.',
185
- shape: {},
162
+ description: 'List the LLM providers configured in your organization, with the credential backing each one.',
163
+ input: z.object({}),
186
164
  run: () => proxy.listProviders(),
187
165
  },
188
166
  {
189
167
  name: 'almyty_add_provider',
190
- description: 'Add an LLM provider backed by an existing connection. Connect the vendor account first with `npx @almyty/connections connect <vendor>` and pass the connection id here. ' +
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. ' +
191
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.',
192
- shape: {
170
+ input: z.object({
193
171
  name: z.string().describe('Display name for the provider'),
194
172
  type: z.string().describe('Provider type (openai, anthropic, gemini, azure, bedrock, ...)'),
195
- credentialId: z.string().describe('Id of an existing connection, from `npx @almyty/connections list`'),
196
- },
173
+ credentialId: z.string().describe('Id of an existing credential, from `npx @almyty/credentials list`'),
174
+ }),
197
175
  run: (args) => proxy.addProvider({ name: args.name, type: args.type, credentialId: args.credentialId, configuration: {} }),
198
176
  },
199
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);
200
228
  for (const tool of management) {
201
- server.tool(tool.name, tool.description, tool.shape, async (args) => {
229
+ server.registerTool(tool.name, { description: tool.description, inputSchema: tool.input }, async (args) => {
202
230
  try {
203
231
  return textResult(await tool.run(args));
204
232
  }
@@ -208,15 +236,16 @@ async function main() {
208
236
  });
209
237
  }
210
238
  // Server info, answered from whatever discovery has managed so far.
211
- 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) => ({
212
240
  contents: [{
213
241
  uri: uri.href,
214
242
  mimeType: 'application/json',
215
243
  text: JSON.stringify({
216
- server: ALMYTY_URL,
244
+ server: url,
217
245
  version: VERSION,
218
246
  gatewayId: ALMYTY_GATEWAY_ID || 'all',
219
247
  mode: ALMYTY_MODE,
248
+ protocol: { client: era, upstream: proxy.upstreamEra },
220
249
  discovered: catalog.discovered,
221
250
  tools: catalog.tools.length,
222
251
  skills: catalog.skills.length,
@@ -224,35 +253,16 @@ async function main() {
224
253
  }, null, 2),
225
254
  }],
226
255
  }));
227
- // ── Connect, then discover ───────────────────────────────────────
228
- // This order is the point: the client gets its handshake even when the
229
- // backend is unreachable, so the editor shows a server that explains the
230
- // problem instead of one that died.
231
- const transport = new StdioServerTransport();
232
- await server.connect(transport);
233
- log(`ready on stdio (mode: ${ALMYTY_MODE}, ${management.length} management tools)`);
234
- await catalog.refresh();
235
- if (catalog.lastError) {
236
- log(`gateway discovery failed: ${catalog.lastError}`);
237
- log('the management tools still work; almyty_execute will report this until discovery succeeds');
238
- }
239
- else {
240
- log(`${catalog.tools.length} gateway tools, ${catalog.skills.length} skills`);
241
- }
242
- // Skills as prompts, loaded on demand rather than held in context.
243
- const promptNames = uniquePromptNames(catalog.skills.map((s) => s.name));
244
- catalog.skills.forEach((skill, i) => {
245
- server.prompt(promptNames[i], `How to use: ${skill.name} (${skill.toolCount} tools)`, async () => ({
246
- messages: [{ role: 'user', content: { type: 'text', text: skill.content } }],
247
- }));
248
- });
249
- // A compact index of everything available, as one prompt.
250
- server.prompt('almyty-overview', `Overview: ${catalog.tools.length} API tools available via almyty`, async () => {
256
+ // A compact index of everything available, as one prompt. Registered
257
+ // with the instance: its description gets the tool count once discovery
258
+ // has run.
259
+ let promptNames = [];
260
+ const overview = server.registerPrompt('almyty-overview', { description: 'Overview: the API tools available via almyty' }, async () => {
251
261
  await catalog.ensureFresh();
252
262
  const lines = [
253
263
  '# almyty API tools',
254
264
  '',
255
- `Connected to: ${ALMYTY_URL}`,
265
+ `Connected to: ${url}`,
256
266
  ALMYTY_GATEWAY_ID ? `Gateway: ${ALMYTY_GATEWAY_ID}` : 'Gateway: all',
257
267
  '',
258
268
  ];
@@ -266,41 +276,113 @@ async function main() {
266
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', '');
267
277
  return { messages: [{ role: 'user', content: { type: 'text', text: lines.filter(Boolean).join('\n') } }] };
268
278
  });
269
- if (ALMYTY_MODE === 'full') {
270
- // Every gateway tool individually. The JSON Schema the gateway returns
271
- // is converted to the Zod shape the SDK wants; handing it the raw
272
- // schema left the SDK with no usable parameter types.
273
- for (const tool of catalog.tools) {
274
- 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;
275
293
  try {
276
- return textResult(await proxy.callTool(tool.name, args));
294
+ config = gatewayToolConfig(tool);
277
295
  }
278
296
  catch (error) {
279
- return errorResult(error);
297
+ log(`skipping gateway tool ${tool.name}: its schema is not valid JSON Schema (${error.message})`);
298
+ continue;
280
299
  }
281
- });
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
+ }
282
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;
283
319
  }
284
- // Registrations happened after the handshake, so tell the client its
285
- // lists changed. A client that does not care ignores it.
286
- // Feature-detected rather than called outright: these notifications are
287
- // a courtesy, and nothing here depends on one arriving or on a particular
288
- // SDK version carrying them.
289
- const lowLevel = server.server;
290
- const notify = (method) => {
291
- const fn = lowLevel?.[method];
292
- if (typeof fn !== 'function')
293
- return;
294
- try {
295
- 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');
296
364
  }
297
- catch {
298
- // 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'})`);
299
367
  }
300
- };
301
- if (ALMYTY_MODE === 'full' && catalog.tools.length > 0)
302
- notify('sendToolListChanged');
303
- 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)`);
304
386
  }
305
387
  function printHelp() {
306
388
  console.log(`
@@ -318,9 +400,10 @@ Usage:
318
400
  npx @almyty/mcp-server Serve every gateway the token can see
319
401
  npx @almyty/mcp-server --help This help
320
402
  npx @almyty/mcp-server --version Print the version
321
-
322
403
  The server speaks MCP over stdio: stdout carries the protocol and every
323
404
  diagnostic goes to stderr. It is meant to be launched by an MCP client, not
405
+ run by hand. It speaks MCP 2026-07-28 and the earlier versions (2024-11-05 to
406
+ 2025-11-25) alike: the client's first message decides.
324
407
  run by hand.
325
408
 
326
409
  Modes (ALMYTY_MODE):
@@ -337,9 +420,9 @@ Management tools (both modes), for building on almyty from your assistant:
337
420
  almyty_list_agents almyty_create_agent almyty_invoke_agent
338
421
  almyty_list_providers almyty_add_provider
339
422
 
340
- almyty_add_provider takes a connection id, never an API key: a key passed as
423
+ almyty_add_provider takes a credential id, never an API key: a key passed as
341
424
  a tool argument would land in the assistant's transcript and the editor's
342
- logs. Make the connection first with \`npx @almyty/connections connect <vendor>\`.
425
+ logs. Add the credential first with \`npx @almyty/credentials add <vendor>\`.
343
426
 
344
427
  Authentication:
345
428
  npx @almyty/auth login Browser-based login (one-time setup)
@@ -349,6 +432,12 @@ Environment:
349
432
  ALMYTY_TOKEN Token (otherwise read from ~/.almyty/credentials.json)
350
433
  ALMYTY_GATEWAY_ID Gateway as "orgSlug/gatewaySlug" (alternative to the positional arg)
351
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)
352
441
 
353
442
  Configuration:
354
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
  /**
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.0",
3
+ "version": "1.5.2",
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.2.0",
40
- "@modelcontextprotocol/sdk": "^1.7.0",
41
- "zod": "^3.22.0"
39
+ "@almyty/client": "^1.5.1",
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
- }