@almyty/mcp-server 1.1.1 → 1.3.0

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
@@ -1,373 +1,384 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * @almyty/mcp-server — Skill-first API proxy for any LLM
3
+ * @almyty/mcp-server — skill-first API proxy for any MCP client
4
4
  *
5
- * Instead of dumping N tool schemas into context (N * ~200 tokens each),
6
- * this injects:
7
- * 1. Skills (compact markdown prompts) — the LLM's knowledge layer
8
- * 2. ONE universal executor tool — handles all API calls
9
- * 3. ONE search tool — finds the right skill/tool on demand
5
+ * Instead of putting N tool schemas in context (N * ~200 tokens each), this
6
+ * registers:
7
+ * 1. skills (compact markdown prompts) loaded on demand,
8
+ * 2. one universal executor, `almyty_execute`,
9
+ * 3. one search tool, `almyty_search`.
10
10
  *
11
- * Token comparison:
12
- * Traditional MCP: 20 tools = ~4,000 tokens always in context
13
- * Skill-first: 2 tools + skills on-demand = ~300 tokens base
11
+ * The model reads a skill to learn a workflow, then calls almyty_execute with
12
+ * a tool name and parameters.
14
13
  *
15
- * The LLM reads a skill to understand a workflow, then calls almyty_execute
16
- * with the tool name and parameters. Skills are loaded on demand via
17
- * MCP prompts — only when the LLM actually needs them.
14
+ * Two rules this file lives by:
18
15
  *
19
- * Works with every major AI coding assistant:
20
- * - Claude Code (.mcp.json / .claude/skills/)
21
- * - Cursor (.cursor/mcp.json)
22
- * - Windsurf (~/.codeium/windsurf/mcp_config.json)
23
- * - OpenAI Codex CLI (~/.codex/config.toml)
24
- * - GitHub Copilot (.vscode/mcp.json)
25
- * - Google Gemini CLI (~/.gemini/settings.json)
16
+ * **stdout is the protocol.** Every diagnostic goes to stderr; one stray
17
+ * console.log on stdout corrupts the JSON-RPC stream and the host editor
18
+ * loses the server with no useful error.
26
19
  *
27
- * Environment variables:
28
- * ALMYTY_URL - Base URL of the almyty backend (default: https://api.almyty.com)
29
- * ALMYTY_TOKEN - JWT Bearer token for authentication
30
- * ALMYTY_GATEWAY_ID - Optional: scope to a specific gateway
31
- * ALMYTY_MODE - "skill-first" (default) | "full" (registers all tools individually)
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.
32
24
  */
33
25
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
34
26
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
35
27
  import { z } from 'zod';
36
28
  import { resolveCredentials } from './auth.js';
37
29
  import { AlmytyProxy } from './proxy.js';
30
+ import { ToolCatalog, searchResultText, uniquePromptNames, upstreamErrorText } from './catalog.js';
31
+ import { EXIT, EXIT_CODE_HELP, exitCodeFor } from './exit-codes.js';
32
+ import { buildZodShape } from './schema.js';
33
+ import { VERSION } from './version.js';
38
34
  // Accept gateway as positional arg or env var:
39
35
  // npx @almyty/mcp-server acme/petstore
40
36
  // ALMYTY_GATEWAY_ID=acme/petstore npx @almyty/mcp-server
41
37
  const ALMYTY_GATEWAY_ID = process.argv[2] || process.env.ALMYTY_GATEWAY_ID;
42
38
  const ALMYTY_MODE = (process.env.ALMYTY_MODE || 'skill-first');
43
- /**
44
- * Sanitize a skill name into a valid MCP prompt identifier.
45
- * MCP prompt names should be safe identifiers — replace anything outside
46
- * [a-zA-Z0-9_-] (e.g. slashes from `petstore/pets`) with underscores so
47
- * the registration doesn't blow up on real-world skill names.
48
- */
49
- function sanitizePromptName(name) {
50
- return name
51
- .replace(/[^a-zA-Z0-9_-]/g, '_')
52
- .replace(/_{2,}/g, '_')
53
- .replace(/^_+|_+$/g, '') || 'skill';
39
+ /** Never stdout: that is the protocol stream. */
40
+ function log(message) {
41
+ process.stderr.write(`almyty: ${message}\n`);
42
+ }
43
+ /** A tool result the model can act on, rather than a raw upstream body. */
44
+ function errorResult(err) {
45
+ return {
46
+ content: [{ type: 'text', text: upstreamErrorText(err) }],
47
+ isError: true,
48
+ };
49
+ }
50
+ function textResult(result) {
51
+ return {
52
+ content: [{
53
+ type: 'text',
54
+ text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),
55
+ }],
56
+ };
54
57
  }
55
58
  async function main() {
56
59
  // Resolve token: env var > ~/.almyty/credentials.json
57
60
  const creds = resolveCredentials();
58
61
  if (!creds) {
59
- console.error('Error: No authentication token found.\n' +
60
- 'Set ALMYTY_TOKEN environment variable or run: npx @almyty/auth login');
61
- process.exit(1);
62
+ log('no authentication token found.\n' +
63
+ ' Set ALMYTY_TOKEN, or run: npx @almyty/auth login');
64
+ process.exit(EXIT.AUTH);
62
65
  }
63
66
  const ALMYTY_URL = creds.url;
64
67
  const proxy = new AlmytyProxy(ALMYTY_URL, creds.token, ALMYTY_GATEWAY_ID);
65
- // Fetch tools + skills from backend
66
- const [tools, skills] = await Promise.all([
67
- proxy.fetchTools(),
68
- proxy.fetchSkills(),
69
- ]);
70
- console.error(`almyty: ${tools.length} tools, ${skills.length} skills (mode: ${ALMYTY_MODE})`);
71
- const server = new McpServer({
72
- name: 'almyty',
73
- version: '1.0.0',
74
- });
68
+ const catalog = new ToolCatalog(proxy, { warn: (m) => log(m) });
69
+ const server = new McpServer({ name: 'almyty', version: VERSION });
70
+ // ── Gateway tools ────────────────────────────────────────────────
75
71
  if (ALMYTY_MODE === 'skill-first') {
76
- // =====================================================
77
- // SKILL-FIRST MODE (default) — minimal token overhead
78
- // =====================================================
79
- // Register only 2 tools instead of N:
80
- // 1. almyty_execute — universal tool executor
81
- // 2. almyty_search — find tools by query
82
- //
83
- // Skills are registered as prompts (loaded on-demand).
84
- // The LLM reads a skill, learns the workflow, then calls
85
- // almyty_execute with the right tool name + params.
86
- // =====================================================
87
- // Build a compact tool index for the search tool
88
- const toolIndex = tools.map(t => ({
89
- name: t.name,
90
- description: t.description || '',
91
- }));
92
- // --- Universal executor ---
93
- // ONE tool that can call ANY almyty tool by name.
94
- // ~150 tokens in context instead of N * ~200 tokens.
95
- 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.', {
96
- tool_name: z.string().describe('Name of the almyty tool to execute (from skill instructions)'),
97
- parameters: z.record(z.unknown()).describe('Parameters for the tool (see skill for required params)'),
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)'),
98
78
  }, async (args) => {
99
79
  try {
100
- const result = await proxy.callTool(args.tool_name, args.parameters);
101
- return {
102
- content: [{
103
- type: 'text',
104
- text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),
105
- }],
106
- };
80
+ return textResult(await proxy.callTool(args.tool_name, args.parameters));
107
81
  }
108
82
  catch (error) {
109
- return {
110
- content: [{ type: 'text', text: `Error: ${error.message}` }],
111
- isError: true,
112
- };
83
+ return errorResult(error);
113
84
  }
114
85
  });
115
- // --- Search tool ---
116
- // Helps the LLM find the right tool/skill without having all schemas in context.
117
- server.tool('almyty_search', 'Search available API tools by keyword. Returns matching tool names and descriptions. Use this to discover which tools are available before calling almyty_execute.', {
118
- query: z.string().describe('Search query (e.g., "create pet", "list users", "payment")'),
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.'),
119
88
  }, async (args) => {
120
- const query = args.query.toLowerCase();
121
- const matches = toolIndex.filter(t => t.name.toLowerCase().includes(query) ||
122
- t.description.toLowerCase().includes(query));
123
- if (matches.length === 0) {
124
- return {
125
- content: [{
126
- type: 'text',
127
- text: `No tools found matching "${args.query}". Available tools: ${toolIndex.slice(0, 10).map(t => t.name).join(', ')}${toolIndex.length > 10 ? ` ... and ${toolIndex.length - 10} more` : ''}`,
128
- }],
129
- };
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));
130
95
  }
131
- const resultText = matches.slice(0, 20).map(t => `- **${t.name}**: ${t.description}`).join('\n');
132
- return {
133
- content: [{
134
- type: 'text',
135
- text: `Found ${matches.length} tools:\n${resultText}\n\nLoad the relevant skill prompt for detailed usage instructions, then call almyty_execute.`,
136
- }],
137
- };
96
+ return textResult(searchResultText(args.query, catalog.search(args.query), catalog.tools));
138
97
  });
139
98
  }
140
- else {
141
- // =====================================================
142
- // FULL MODE — registers every tool individually
143
- // Higher token overhead but works without skill prompts.
144
- // =====================================================
145
- for (const tool of tools) {
146
- const schema = tool.inputSchema || { type: 'object', properties: {} };
147
- server.tool(tool.name, tool.description || `Tool: ${tool.name}`, schema, async (args) => {
148
- try {
149
- const result = await proxy.callTool(tool.name, args);
150
- return {
151
- content: [{
152
- type: 'text',
153
- text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),
154
- }],
155
- };
156
- }
157
- catch (error) {
158
- return {
159
- content: [{ type: 'text', text: `Error: ${error.message}` }],
160
- isError: true,
161
- };
162
- }
163
- });
164
- }
165
- }
166
- // =====================================================
167
- // SKILLS AS PROMPTS — loaded on demand, not in context
168
- // =====================================================
169
- // Each skill is ~100-250 tokens. The LLM loads only the
170
- // skill it needs via prompts/get, instead of having all
171
- // N tool schemas (~200 tokens each) always in context.
172
- // =====================================================
173
- // Track sanitized prompt names to avoid collisions when two skills
174
- // sanitize to the same identifier (e.g. `petstore/pets` and
175
- // `petstore-pets` both become `petstore_pets`).
176
- const usedPromptNames = new Set();
177
- for (const skill of skills) {
178
- let promptName = `skill-${sanitizePromptName(skill.name)}`;
179
- if (usedPromptNames.has(promptName)) {
180
- let suffix = 2;
181
- while (usedPromptNames.has(`${promptName}-${suffix}`))
182
- suffix++;
183
- promptName = `${promptName}-${suffix}`;
184
- }
185
- usedPromptNames.add(promptName);
186
- server.prompt(promptName, `How to use: ${skill.name} (${skill.toolCount} tools)`, async () => ({
187
- messages: [{
188
- role: 'user',
189
- content: {
190
- type: 'text',
191
- text: skill.content,
192
- },
193
- }],
194
- }));
195
- }
196
- // Overview prompt — compact index of all available skills
197
- if (skills.length > 0 || tools.length > 0) {
198
- server.prompt('almyty-overview', `Overview: ${tools.length} API tools available via almyty`, async () => {
199
- const lines = [
200
- '# almyty API Tools',
201
- '',
202
- `Connected to: ${ALMYTY_URL}`,
203
- ALMYTY_GATEWAY_ID ? `Gateway: ${ALMYTY_GATEWAY_ID}` : '',
204
- '',
205
- `## ${tools.length} tools available`,
206
- '',
207
- ...tools.map(t => `- \`${t.name}\`: ${t.description || 'No description'}`),
208
- '',
209
- ];
210
- if (skills.length > 0) {
211
- lines.push(`## ${skills.length} skills (detailed usage guides)`, '', ...skills.map(s => `- \`skill-${s.name}\`: ${s.toolCount} tools`), '');
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 = [
103
+ {
104
+ name: 'almyty_list_apis',
105
+ description: 'List all connected APIs in your organization.',
106
+ shape: {},
107
+ run: () => proxy.listApis(),
108
+ },
109
+ {
110
+ name: 'almyty_create_api',
111
+ description: 'Connect a new API. Provide a name, type (openapi/graphql/soap/protobuf/sdk), and base URL.',
112
+ shape: {
113
+ name: z.string().describe('Human-readable API name'),
114
+ type: z.enum(['openapi', 'graphql', 'soap', 'protobuf', 'sdk']).describe('Schema type'),
115
+ baseUrl: z.string().optional().describe('API base URL (not needed for SDK type)'),
116
+ },
117
+ run: (args) => proxy.createApi(args),
118
+ },
119
+ {
120
+ name: 'almyty_import_schema',
121
+ description: 'Import an API schema and auto-generate tools. Provide the API ID and a schema URL.',
122
+ shape: {
123
+ apiId: z.string().describe('ID of the API to import into'),
124
+ schemaUrl: z.string().describe('URL of the schema (e.g. an OpenAPI JSON endpoint)'),
125
+ generateTools: z.boolean().default(true).describe('Auto-generate tools from operations'),
126
+ },
127
+ run: (args) => proxy.importSchema(args.apiId, { schemaUrl: args.schemaUrl, generateTools: args.generateTools }),
128
+ },
129
+ {
130
+ name: 'almyty_list_gateways',
131
+ description: 'List all gateways in your organization.',
132
+ shape: {},
133
+ run: () => proxy.listGateways(),
134
+ },
135
+ {
136
+ 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: {
139
+ name: z.string().describe('Gateway name'),
140
+ type: z.enum(['mcp', 'a2a', 'utcp', 'skills']).describe('Protocol type'),
141
+ 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: {} }),
146
+ },
147
+ {
148
+ name: 'almyty_assign_tool',
149
+ description: 'Assign a tool to a tool-kind gateway.',
150
+ shape: {
151
+ gatewayId: z.string().describe('Gateway ID'),
152
+ toolId: z.string().describe('Tool ID to assign'),
153
+ },
154
+ run: (args) => proxy.assignToolToGateway(args.gatewayId, args.toolId),
155
+ },
156
+ {
157
+ name: 'almyty_list_agents',
158
+ description: 'List all agents in your organization.',
159
+ shape: {},
160
+ run: () => proxy.listAgents(),
161
+ },
162
+ {
163
+ name: 'almyty_create_agent',
164
+ description: 'Create an agent. Workflow agents run a visual DAG pipeline; autonomous agents run from instructions plus tool access.',
165
+ shape: {
166
+ name: z.string().describe('Agent name'),
167
+ description: z.string().optional().describe('What the agent does'),
168
+ mode: z.enum(['workflow', 'autonomous']).default('autonomous').describe('workflow = visual pipeline, autonomous = instruction-driven'),
169
+ instructions: z.string().optional().describe('Instructions for autonomous agents'),
170
+ },
171
+ run: (args) => proxy.createAgent(args),
172
+ },
173
+ {
174
+ name: 'almyty_invoke_agent',
175
+ description: 'Invoke an agent with input. Returns the agent execution result.',
176
+ shape: {
177
+ agentId: z.string().describe('Agent ID'),
178
+ input: z.record(z.unknown()).describe('Input data for the agent'),
179
+ },
180
+ run: (args) => proxy.invokeAgent(args.agentId, args.input),
181
+ },
182
+ {
183
+ name: 'almyty_list_providers',
184
+ description: 'List the LLM providers configured in your organization, with the connection backing each one.',
185
+ shape: {},
186
+ run: () => proxy.listProviders(),
187
+ },
188
+ {
189
+ 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. ' +
191
+ '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: {
193
+ name: z.string().describe('Display name for the provider'),
194
+ 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
+ },
197
+ run: (args) => proxy.addProvider({ name: args.name, type: args.type, credentialId: args.credentialId, configuration: {} }),
198
+ },
199
+ ];
200
+ for (const tool of management) {
201
+ server.tool(tool.name, tool.description, tool.shape, async (args) => {
202
+ try {
203
+ return textResult(await tool.run(args));
204
+ }
205
+ catch (error) {
206
+ return errorResult(error);
212
207
  }
213
- 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', '');
214
- return {
215
- messages: [{
216
- role: 'user',
217
- content: { type: 'text', text: lines.filter(Boolean).join('\n') },
218
- }],
219
- };
220
208
  });
221
209
  }
222
- // Server info resource
210
+ // Server info, answered from whatever discovery has managed so far.
223
211
  server.resource('almyty-info', 'almyty://info', async (uri) => ({
224
212
  contents: [{
225
213
  uri: uri.href,
226
214
  mimeType: 'application/json',
227
215
  text: JSON.stringify({
228
216
  server: ALMYTY_URL,
217
+ version: VERSION,
229
218
  gatewayId: ALMYTY_GATEWAY_ID || 'all',
230
219
  mode: ALMYTY_MODE,
231
- tools: tools.length,
232
- skills: skills.length,
220
+ discovered: catalog.discovered,
221
+ tools: catalog.tools.length,
222
+ skills: catalog.skills.length,
223
+ discoveryError: catalog.lastError,
233
224
  }, null, 2),
234
225
  }],
235
226
  }));
236
- // =====================================================
237
- // MANAGEMENT TOOLS — control the almyty platform itself
238
- // =====================================================
239
- // These tools let LLMs manage almyty: create APIs, import
240
- // schemas, generate tools, set up gateways, build agents.
241
- // Available in both modes (skill-first and full).
242
- server.tool('almyty_list_apis', 'List all connected APIs in your organization.', {}, async () => {
243
- const result = await proxy.listApis();
244
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
245
- });
246
- server.tool('almyty_create_api', 'Connect a new API. Provide a name, type (openapi/graphql/soap/protobuf/sdk), and base URL.', {
247
- name: z.string().describe('Human-readable API name'),
248
- type: z.enum(['openapi', 'graphql', 'soap', 'protobuf', 'sdk']).describe('Schema type'),
249
- baseUrl: z.string().optional().describe('API base URL (not needed for SDK type)'),
250
- }, async (args) => {
251
- const result = await proxy.createApi(args);
252
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
253
- });
254
- server.tool('almyty_import_schema', 'Import an API schema and auto-generate tools. Provide the API ID and a schema URL.', {
255
- apiId: z.string().describe('ID of the API to import into'),
256
- schemaUrl: z.string().describe('URL of the schema (e.g. OpenAPI JSON endpoint)'),
257
- generateTools: z.boolean().default(true).describe('Auto-generate tools from operations'),
258
- }, async (args) => {
259
- const result = await proxy.importSchema(args.apiId, { schemaUrl: args.schemaUrl, generateTools: args.generateTools });
260
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
261
- });
262
- server.tool('almyty_list_gateways', 'List all gateways in your organization.', {}, async () => {
263
- const result = await proxy.listGateways();
264
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
265
- });
266
- server.tool('almyty_create_gateway', 'Create a gateway to expose tools OR an agent via a protocol (MCP, A2A, UTCP, Skills). Use kind="tool" for a tool gateway or kind="agent" for an agent gateway.', {
267
- name: z.string().describe('Gateway name'),
268
- type: z.enum(['mcp', 'a2a', 'utcp', 'skills']).describe('Protocol type'),
269
- endpoint: z.string().describe('URL slug for the gateway endpoint'),
270
- kind: z.enum(['tool', 'agent']).default('tool').describe('What the gateway exposes: tools or a single agent'),
271
- agentId: z.string().optional().describe('Agent ID (required when kind is "agent")'),
272
- }, async (args) => {
273
- const result = await proxy.createGateway({ ...args, configuration: {} });
274
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
275
- });
276
- server.tool('almyty_assign_tool', 'Assign a tool to a tool-kind gateway.', {
277
- gatewayId: z.string().describe('Gateway ID'),
278
- toolId: z.string().describe('Tool ID to assign'),
279
- }, async (args) => {
280
- const result = await proxy.assignToolToGateway(args.gatewayId, args.toolId);
281
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
282
- });
283
- server.tool('almyty_list_agents', 'List all agents in your organization.', {}, async () => {
284
- const result = await proxy.listAgents();
285
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
286
- });
287
- server.tool('almyty_create_agent', 'Create a new agent. Workflow agents use a visual DAG pipeline. Autonomous agents use instructions + tool access.', {
288
- name: z.string().describe('Agent name'),
289
- description: z.string().optional().describe('What the agent does'),
290
- mode: z.enum(['workflow', 'autonomous']).default('autonomous').describe('workflow = visual pipeline, autonomous = instruction-driven'),
291
- instructions: z.string().optional().describe('Instructions for autonomous agents'),
292
- }, async (args) => {
293
- const result = await proxy.createAgent(args);
294
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
295
- });
296
- server.tool('almyty_invoke_agent', 'Invoke an agent with input. Returns the agent execution result.', {
297
- agentId: z.string().describe('Agent ID'),
298
- input: z.record(z.unknown()).describe('Input data for the agent'),
299
- }, async (args) => {
300
- const result = await proxy.invokeAgent(args.agentId, args.input);
301
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
302
- });
303
- server.tool('almyty_add_provider', 'Add an LLM provider (OpenAI, Anthropic, etc.).', {
304
- name: z.string().describe('Display name'),
305
- type: z.string().describe('Provider type (openai, anthropic, gemini, azure, bedrock, etc.)'),
306
- apiKey: z.string().describe('API key for the provider'),
307
- }, async (args) => {
308
- const result = await proxy.addProvider({ name: args.name, type: args.type, configuration: { apiKey: args.apiKey } });
309
- return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
310
- });
311
- process.stderr.write(`almyty: ${tools.length} gateway tools, ${skills.length} skills, 10 management tools (mode: ${ALMYTY_MODE})\n`);
312
- // Connect via stdio
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.
313
231
  const transport = new StdioServerTransport();
314
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 () => {
251
+ await catalog.ensureFresh();
252
+ const lines = [
253
+ '# almyty API tools',
254
+ '',
255
+ `Connected to: ${ALMYTY_URL}`,
256
+ ALMYTY_GATEWAY_ID ? `Gateway: ${ALMYTY_GATEWAY_ID}` : 'Gateway: all',
257
+ '',
258
+ ];
259
+ if (catalog.lastError && !catalog.discovered) {
260
+ lines.push(`Discovery failed: ${upstreamErrorText(new Error(catalog.lastError))}`, '');
261
+ }
262
+ lines.push(`## ${catalog.tools.length} tools available`, '', ...catalog.tools.map((t) => `- \`${t.name}\`: ${t.description || 'No description'}`), '');
263
+ if (catalog.skills.length > 0) {
264
+ lines.push(`## ${catalog.skills.length} skills (detailed usage guides)`, '', ...catalog.skills.map((s, i) => `- \`${promptNames[i]}\`: ${s.toolCount} tools`), '');
265
+ }
266
+ 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
+ return { messages: [{ role: 'user', content: { type: 'text', text: lines.filter(Boolean).join('\n') } }] };
268
+ });
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) => {
275
+ try {
276
+ return textResult(await proxy.callTool(tool.name, args));
277
+ }
278
+ catch (error) {
279
+ return errorResult(error);
280
+ }
281
+ });
282
+ }
283
+ }
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);
296
+ }
297
+ catch {
298
+ // A client that refuses the notification changes nothing.
299
+ }
300
+ };
301
+ if (ALMYTY_MODE === 'full' && catalog.tools.length > 0)
302
+ notify('sendToolListChanged');
303
+ notify('sendPromptListChanged');
315
304
  }
316
- // Handle subcommands (check before main() uses argv[2] as gateway ID)
317
- const subcommand = process.argv[2];
318
- if (subcommand === 'login' || subcommand === 'logout' || subcommand === 'whoami') {
319
- // Auth lives in @almyty/auth. Redirect rather than silently doing
320
- // nothing — users typing the old commands should see the new entry point.
321
- console.error(`Authentication moved to @almyty/auth.`);
322
- console.error(` npx @almyty/auth ${subcommand}`);
323
- process.exit(1);
324
- }
325
- else if (subcommand === '--help' || subcommand === '-h') {
305
+ function printHelp() {
326
306
  console.log(`
327
- @almyty/mcp-server — Skill-first API proxy for any LLM
307
+ @almyty/mcp-server v${VERSION} — skill-first API proxy for any MCP client
328
308
 
329
- Turn any API into AI skills. Instead of dumping tool schemas into context
330
- (expensive), this injects compact skills that teach the LLM workflows,
331
- plus a single universal executor.
309
+ Turn any API into AI skills. Instead of putting tool schemas in context
310
+ (expensive), this serves compact skills that teach the model workflows, plus a
311
+ single universal executor.
332
312
 
333
- Token overhead comparison:
334
313
  Traditional MCP: 20 tools = ~4,000 tokens/turn (always in context)
335
314
  Skill-first: 2 tools = ~300 tokens/turn (skills loaded on demand)
336
315
 
337
316
  Usage:
338
- npx @almyty/mcp-server <org/gateway> Start server for a specific gateway
339
- npx @almyty/mcp-server Start server (all gateways)
317
+ npx @almyty/mcp-server <org/gateway> Serve one gateway
318
+ npx @almyty/mcp-server Serve every gateway the token can see
319
+ npx @almyty/mcp-server --help This help
320
+ npx @almyty/mcp-server --version Print the version
340
321
 
341
- Examples:
342
- npx @almyty/mcp-server acme/petstore
343
- claude mcp add petstore -- npx -y @almyty/mcp-server acme/petstore
322
+ The server speaks MCP over stdio: stdout carries the protocol and every
323
+ diagnostic goes to stderr. It is meant to be launched by an MCP client, not
324
+ run by hand.
325
+
326
+ Modes (ALMYTY_MODE):
327
+ skill-first (default) almyty_execute + almyty_search, and skills as prompts.
328
+ Minimal context. The tool index is re-read when it goes stale,
329
+ so a tool added in almyty is found without a restart.
330
+ full Every gateway tool registered individually. Traditional MCP,
331
+ higher context cost. The list is read once at startup and the
332
+ client is notified when it arrives.
333
+
334
+ Management tools (both modes), for building on almyty from your assistant:
335
+ almyty_list_apis almyty_create_api almyty_import_schema
336
+ almyty_list_gateways almyty_create_gateway almyty_assign_tool
337
+ almyty_list_agents almyty_create_agent almyty_invoke_agent
338
+ almyty_list_providers almyty_add_provider
339
+
340
+ almyty_add_provider takes a connection id, never an API key: a key passed as
341
+ 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>\`.
344
343
 
345
344
  Authentication:
346
345
  npx @almyty/auth login Browser-based login (one-time setup)
347
346
 
348
347
  Environment:
349
348
  ALMYTY_URL Base URL (default: https://api.almyty.com)
350
- ALMYTY_TOKEN API key (auto-read from ~/.almyty/credentials.json)
351
- ALMYTY_GATEWAY_ID Gateway (alternative to positional arg)
349
+ ALMYTY_TOKEN Token (otherwise read from ~/.almyty/credentials.json)
350
+ ALMYTY_GATEWAY_ID Gateway as "orgSlug/gatewaySlug" (alternative to the positional arg)
352
351
  ALMYTY_MODE "skill-first" (default) | "full"
353
352
 
354
- Modes:
355
- skill-first 2 tools (almyty_execute + almyty_search) + skills as prompts
356
- Minimal token overhead. LLM loads skills on demand.
357
- full All tools registered individually (traditional MCP)
358
- Higher overhead but works without prompt loading.
359
-
360
353
  Configuration:
361
-
362
354
  Claude Code: claude mcp add petstore -- npx -y @almyty/mcp-server acme/petstore
363
- Cursor: .cursor/mcp.json → { "mcpServers": { "petstore": { "command": "npx", "args": ["-y", "@almyty/mcp-server", "acme/petstore"] } } }
364
- Copilot: .vscode/mcp.json → { "servers": { "almyty": { "command": "npx", "args": ["-y", "@almyty/mcp-server"] } } }
365
- Gemini: ~/.gemini/settings.json → { "mcpServers": { "almyty": { ... } } }
355
+ Cursor: .cursor/mcp.json -> { "mcpServers": { "petstore": { "command": "npx", "args": ["-y", "@almyty/mcp-server", "acme/petstore"] } } }
356
+ Copilot: .vscode/mcp.json -> { "servers": { "almyty": { "command": "npx", "args": ["-y", "@almyty/mcp-server"] } } }
357
+ Gemini: ~/.gemini/settings.json -> { "mcpServers": { "almyty": { ... } } }
358
+
359
+ Exit codes (the same in every almyty CLI):
360
+ ${EXIT_CODE_HELP}
366
361
  `);
367
362
  }
363
+ // Handle subcommands before main() reads argv[2] as a gateway id.
364
+ const subcommand = process.argv[2];
365
+ if (subcommand === 'login' || subcommand === 'logout' || subcommand === 'whoami') {
366
+ // Auth lives in @almyty/auth. Redirect rather than silently doing nothing.
367
+ console.error('Authentication moved to @almyty/auth.');
368
+ console.error(` npx @almyty/auth ${subcommand}`);
369
+ process.exit(EXIT.USAGE);
370
+ }
371
+ else if (subcommand === '--help' || subcommand === '-h' || subcommand === 'help') {
372
+ printHelp();
373
+ }
374
+ else if (subcommand === '--version' || subcommand === '-v') {
375
+ console.log(VERSION);
376
+ }
368
377
  else {
369
378
  main().catch((err) => {
370
- console.error('Fatal error:', err.message);
371
- process.exit(1);
379
+ log(`fatal: ${upstreamErrorText(err)}`);
380
+ // A token the API rejected leaves with the same code as no token at
381
+ // all, so a supervisor can tell "log in again" from "restart me".
382
+ process.exit(exitCodeFor(err));
372
383
  });
373
384
  }