@almyty/mcp-server 1.5.8 → 1.5.10

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/catalog.d.ts CHANGED
@@ -13,6 +13,8 @@
13
13
  */
14
14
  export interface ToolSummary {
15
15
  name: string;
16
+ /** The display title the gateway gives (the operation's summary), when it gives one. */
17
+ title?: string;
16
18
  description?: string;
17
19
  inputSchema?: Record<string, unknown>;
18
20
  }
@@ -61,7 +63,11 @@ export declare class ToolCatalog {
61
63
  refresh(): Promise<void>;
62
64
  /** Re-ask only when what we hold has aged out. */
63
65
  ensureFresh(): Promise<void>;
64
- /** Substring match over names and descriptions, the cheapest thing that works. */
66
+ /**
67
+ * The tools a query names, best first: its words (stopwords dropped)
68
+ * matched across name, title and description (tool-search.ts). An empty
69
+ * query lists everything.
70
+ */
65
71
  search(query: string): ToolSummary[];
66
72
  }
67
73
  /**
package/dist/catalog.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * So discovery lives here instead: it never throws, it remembers why it
12
12
  * last failed, and it re-asks when what it holds has gone stale.
13
13
  */
14
+ import { searchTools } from './tool-search.js';
14
15
  const DEFAULT_TTL_MS = 60_000;
15
16
  export class ToolCatalog {
16
17
  source;
@@ -73,12 +74,13 @@ export class ToolCatalog {
73
74
  if (this.isStale())
74
75
  await this.refresh();
75
76
  }
76
- /** Substring match over names and descriptions, the cheapest thing that works. */
77
+ /**
78
+ * The tools a query names, best first: its words (stopwords dropped)
79
+ * matched across name, title and description (tool-search.ts). An empty
80
+ * query lists everything.
81
+ */
77
82
  search(query) {
78
- const q = query.trim().toLowerCase();
79
- if (!q)
80
- return this.toolList;
81
- return this.toolList.filter((t) => t.name.toLowerCase().includes(q) || (t.description ?? '').toLowerCase().includes(q));
83
+ return searchTools(this.toolList, query);
82
84
  }
83
85
  }
84
86
  /**
package/dist/index.js CHANGED
@@ -42,8 +42,9 @@ import { resolveCredentials } from './auth.js';
42
42
  import { AlmytyProxy, upstreamEraFromEnv } from './proxy.js';
43
43
  import { ToolCatalog, searchResultText, uniquePromptNames, upstreamErrorText } from './catalog.js';
44
44
  import { EXIT, EXIT_CODE_HELP, exitCodeFor } from './exit-codes.js';
45
- import { gatewayToolConfig, passThroughResult } from './registration.js';
45
+ import { executeResult, gatewayToolConfig, passThroughResult } from './registration.js';
46
46
  import { VERSION } from './version.js';
47
+ import { DrainingStdioTransport } from './stdio-transport.js';
47
48
  // Accept gateway as positional arg or env var:
48
49
  // npx @almyty/mcp-server acme/petstore
49
50
  // ALMYTY_GATEWAY_ID=acme/petstore npx @almyty/mcp-server
@@ -198,7 +199,9 @@ function buildServer(era, deps, discoveredAlready) {
198
199
  }),
199
200
  }, async (args) => {
200
201
  try {
201
- return textResult(await proxy.callTool(args.tool_name, args.parameters));
202
+ // The gateway's result, isError included: an upstream failure (a
203
+ // 401 from the API behind the tool, say) is a failed call, not data.
204
+ return executeResult(await proxy.callToolResult(args.tool_name, args.parameters));
202
205
  }
203
206
  catch (error) {
204
207
  return errorResult(error);
@@ -380,6 +383,9 @@ async function main() {
380
383
  }
381
384
  return buildServer(ctx.era, { proxy, catalog, discovered, url: ALMYTY_URL }, settled);
382
385
  }, {
386
+ // A client may write its requests and close stdin at once; every
387
+ // request already received is answered before the server goes.
388
+ transport: new DrainingStdioTransport(),
383
389
  onerror: (error) => log(`protocol error: ${error.message}`),
384
390
  });
385
391
  log(`ready on stdio (mode: ${ALMYTY_MODE}, ${managementTools(proxy).length} management tools)`);
@@ -26,4 +26,19 @@ export declare function passThroughResult(result: UpstreamToolResult): {
26
26
  structuredContent?: {} | null | undefined;
27
27
  content: any[];
28
28
  };
29
+ /**
30
+ * The result `almyty_execute` hands back: the gateway's first text block
31
+ * (pretty-printed when it is JSON), else the whole result as JSON. A call
32
+ * the gateway marked as failed (the upstream API answered 401, say, or the
33
+ * arguments were refused) stays marked: `isError` goes through, with the
34
+ * gateway's own error text, so the model reads it as a failure rather than
35
+ * as data.
36
+ */
37
+ export declare function executeResult(result: UpstreamToolResult): {
38
+ isError?: true | undefined;
39
+ content: {
40
+ type: "text";
41
+ text: string;
42
+ }[];
43
+ };
29
44
  export {};
@@ -81,3 +81,30 @@ export function passThroughResult(result) {
81
81
  ...(result.isError ? { isError: true } : {}),
82
82
  };
83
83
  }
84
+ /**
85
+ * The result `almyty_execute` hands back: the gateway's first text block
86
+ * (pretty-printed when it is JSON), else the whole result as JSON. A call
87
+ * the gateway marked as failed (the upstream API answered 401, say, or the
88
+ * arguments were refused) stays marked: `isError` goes through, with the
89
+ * gateway's own error text, so the model reads it as a failure rather than
90
+ * as data.
91
+ */
92
+ export function executeResult(result) {
93
+ const first = result.content.find((c) => c?.type === 'text' && typeof c.text === 'string' && c.text);
94
+ let text;
95
+ if (first) {
96
+ try {
97
+ text = JSON.stringify(JSON.parse(first.text), null, 2);
98
+ }
99
+ catch {
100
+ text = first.text;
101
+ }
102
+ }
103
+ else {
104
+ text = JSON.stringify(result, null, 2);
105
+ }
106
+ return {
107
+ content: [{ type: 'text', text }],
108
+ ...(result.isError ? { isError: true } : {}),
109
+ };
110
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Stdio transport that answers what it was asked before it goes.
3
+ *
4
+ * The SDK's StdioServerTransport closes the moment stdin reaches EOF. A
5
+ * client that writes its requests and then closes its end of the pipe
6
+ * (`printf '...' | npx @almyty/mcp-server`, or a test harness) got no
7
+ * replies at all: the first message waits for discovery inside the
8
+ * serveStdio factory, EOF arrives meanwhile, the transport closes and the
9
+ * queued requests are dropped. The process exited 0 with an empty stdout.
10
+ *
11
+ * This one reads the same newline-delimited JSON-RPC, but on EOF it stays
12
+ * open until every request already received has been answered (or
13
+ * `drainTimeoutMs` has passed), and only then closes. A
14
+ * `subscriptions/listen` request is a stream that lasts as long as the
15
+ * connection, so it is not waited for.
16
+ */
17
+ import type { Readable, Writable } from 'node:stream';
18
+ import { type JSONRPCMessage, type Transport } from '@modelcontextprotocol/server';
19
+ export interface DrainingStdioOptions {
20
+ /** How long EOF waits for the answers still owed. Default 120 s. */
21
+ drainTimeoutMs?: number;
22
+ }
23
+ export declare class DrainingStdioTransport implements Transport {
24
+ private readonly stdin;
25
+ private readonly stdout;
26
+ onclose?: () => void;
27
+ onerror?: (error: Error) => void;
28
+ onmessage?: Transport['onmessage'];
29
+ private readonly buffer;
30
+ private readonly owed;
31
+ private started;
32
+ private closed;
33
+ private inputEnded;
34
+ private drainTimer?;
35
+ private readonly drainTimeoutMs;
36
+ constructor(stdin?: Readable, stdout?: Writable, options?: DrainingStdioOptions);
37
+ /** Requests received and not yet answered (for tests and diagnostics). */
38
+ get pending(): number;
39
+ private readonly onData;
40
+ private readonly onInputEnd;
41
+ private readonly onStdinError;
42
+ private readonly onStdoutError;
43
+ start(): Promise<void>;
44
+ send(message: JSONRPCMessage): Promise<void>;
45
+ close(): Promise<void>;
46
+ }
@@ -0,0 +1,124 @@
1
+ import { ReadBuffer, serializeMessage, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCErrorResponse, } from '@modelcontextprotocol/server';
2
+ export class DrainingStdioTransport {
3
+ stdin;
4
+ stdout;
5
+ onclose;
6
+ onerror;
7
+ onmessage;
8
+ buffer = new ReadBuffer();
9
+ owed = new Set();
10
+ started = false;
11
+ closed = false;
12
+ inputEnded = false;
13
+ drainTimer;
14
+ drainTimeoutMs;
15
+ constructor(stdin = process.stdin, stdout = process.stdout, options = {}) {
16
+ this.stdin = stdin;
17
+ this.stdout = stdout;
18
+ this.drainTimeoutMs = options.drainTimeoutMs ?? 120_000;
19
+ }
20
+ /** Requests received and not yet answered (for tests and diagnostics). */
21
+ get pending() {
22
+ return this.owed.size;
23
+ }
24
+ onData = (chunk) => {
25
+ try {
26
+ this.buffer.append(chunk);
27
+ }
28
+ catch (error) {
29
+ this.onerror?.(error);
30
+ return;
31
+ }
32
+ for (;;) {
33
+ let message;
34
+ try {
35
+ message = this.buffer.readMessage();
36
+ }
37
+ catch (error) {
38
+ this.onerror?.(error);
39
+ continue;
40
+ }
41
+ if (message === null)
42
+ break;
43
+ if (isJSONRPCRequest(message) && message.method !== 'subscriptions/listen')
44
+ this.owed.add(message.id);
45
+ this.onmessage?.(message);
46
+ }
47
+ };
48
+ onInputEnd = () => {
49
+ if (this.inputEnded)
50
+ return;
51
+ this.inputEnded = true;
52
+ // Every byte read has been parsed and handed on synchronously in
53
+ // onData, so what is owed now is all that will ever be owed.
54
+ if (this.owed.size === 0) {
55
+ void this.close();
56
+ return;
57
+ }
58
+ this.drainTimer = setTimeout(() => {
59
+ this.onerror?.(new Error(`stdin closed with ${this.owed.size} request(s) unanswered after ${this.drainTimeoutMs} ms`));
60
+ void this.close();
61
+ }, this.drainTimeoutMs);
62
+ this.drainTimer.unref?.();
63
+ };
64
+ onStdinError = (error) => this.onerror?.(error);
65
+ onStdoutError = (error) => {
66
+ if (this.closed)
67
+ return;
68
+ this.onerror?.(error);
69
+ void this.close();
70
+ };
71
+ async start() {
72
+ if (this.started)
73
+ throw new Error('DrainingStdioTransport already started');
74
+ this.started = true;
75
+ this.stdin.on('data', this.onData);
76
+ this.stdin.on('error', this.onStdinError);
77
+ this.stdin.on('end', this.onInputEnd);
78
+ this.stdin.on('close', this.onInputEnd);
79
+ this.stdout.on('error', this.onStdoutError);
80
+ if (this.stdin.readableEnded || this.stdin.destroyed)
81
+ setImmediate(this.onInputEnd);
82
+ }
83
+ async send(message) {
84
+ if (this.closed)
85
+ throw new Error('DrainingStdioTransport is closed');
86
+ await new Promise((resolve, reject) => {
87
+ const onError = (error) => reject(error);
88
+ this.stdout.once('error', onError);
89
+ const flushed = this.stdout.write(serializeMessage(message), (error) => {
90
+ this.stdout.off('error', onError);
91
+ if (error)
92
+ reject(error);
93
+ else
94
+ resolve();
95
+ });
96
+ // A full pipe buffer still delivers the callback once drained.
97
+ void flushed;
98
+ });
99
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
100
+ if (message.id !== undefined && message.id !== null)
101
+ this.owed.delete(message.id);
102
+ if (this.inputEnded && this.owed.size === 0)
103
+ void this.close();
104
+ }
105
+ }
106
+ async close() {
107
+ if (this.closed)
108
+ return;
109
+ this.closed = true;
110
+ if (this.drainTimer)
111
+ clearTimeout(this.drainTimer);
112
+ this.stdin.off('data', this.onData);
113
+ this.stdin.off('error', this.onStdinError);
114
+ this.stdin.off('end', this.onInputEnd);
115
+ this.stdin.off('close', this.onInputEnd);
116
+ // Late write failures (EPIPE after the client went) are not news.
117
+ this.stdout.off('error', this.onStdoutError);
118
+ this.stdout.on('error', () => { });
119
+ if (this.stdin.listenerCount('data') === 0)
120
+ this.stdin.pause();
121
+ this.buffer.clear();
122
+ this.onclose?.();
123
+ }
124
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Keyword search over a gateway's tools, for `almyty_search`.
3
+ *
4
+ * The same rules as the keyword half of the backend's code-mode
5
+ * `search_tools` (backend/src/modules/tool-discovery/tool-search.ts): the
6
+ * query is split into words (camelCase, snake_case, kebab-case and
7
+ * punctuation all split), stopwords are dropped, and each remaining word
8
+ * scores the best-weighted field it appears in. A match in the name counts
9
+ * most, then the title (the operation's summary), then the description. A
10
+ * whole word or a word's start counts fully ("pet" finds "pets"); a match
11
+ * anywhere inside a field, half. The whole query appearing in the name earns
12
+ * a bonus. So "get an issue" searches for "issue" and finds `get_issue`.
13
+ *
14
+ * Copied rather than imported: this package is published on its own and
15
+ * cannot depend on backend source. A test checks the stopwords and the word
16
+ * splitting stay the same as the backend's.
17
+ */
18
+ export interface SearchableToolSummary {
19
+ name: string;
20
+ title?: string;
21
+ description?: string;
22
+ }
23
+ /** Words too common to tell tools apart ("which pets are sold" searches for pets and sold). */
24
+ export declare const STOPWORDS: Set<string>;
25
+ /** Lower-cased words, splitting camelCase, snake_case, kebab-case and punctuation. */
26
+ export declare function words(text: string | null | undefined): string[];
27
+ /** The words of a query worth searching for: no stopwords, each once. */
28
+ export declare function queryTerms(query: string | null | undefined): string[];
29
+ /** A tool's score for a query; zero means nothing matched. */
30
+ export declare function keywordScore(tool: SearchableToolSummary, query: string): number;
31
+ /** The tools that match a query, best first (ties by name). An empty query lists every tool as given. */
32
+ export declare function searchTools<T extends SearchableToolSummary>(tools: T[], query: string): T[];
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Keyword search over a gateway's tools, for `almyty_search`.
3
+ *
4
+ * The same rules as the keyword half of the backend's code-mode
5
+ * `search_tools` (backend/src/modules/tool-discovery/tool-search.ts): the
6
+ * query is split into words (camelCase, snake_case, kebab-case and
7
+ * punctuation all split), stopwords are dropped, and each remaining word
8
+ * scores the best-weighted field it appears in. A match in the name counts
9
+ * most, then the title (the operation's summary), then the description. A
10
+ * whole word or a word's start counts fully ("pet" finds "pets"); a match
11
+ * anywhere inside a field, half. The whole query appearing in the name earns
12
+ * a bonus. So "get an issue" searches for "issue" and finds `get_issue`.
13
+ *
14
+ * Copied rather than imported: this package is published on its own and
15
+ * cannot depend on backend source. A test checks the stopwords and the word
16
+ * splitting stay the same as the backend's.
17
+ */
18
+ /** Words too common to tell tools apart ("which pets are sold" searches for pets and sold). */
19
+ export const STOPWORDS = new Set('a an and are as at be by can do does for from get has have how i in is it its me my of on or our please show that the their them there these this to was we what when where which who will with you your'.split(' '));
20
+ /** Lower-cased words, splitting camelCase, snake_case, kebab-case and punctuation. */
21
+ export function words(text) {
22
+ if (!text)
23
+ return [];
24
+ return text
25
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
26
+ .toLowerCase()
27
+ .split(/[^a-z0-9]+/)
28
+ .filter((w) => w.length > 1);
29
+ }
30
+ /** The words of a query worth searching for: no stopwords, each once. */
31
+ export function queryTerms(query) {
32
+ return [...new Set(words(query).filter((w) => !STOPWORDS.has(w)))];
33
+ }
34
+ const FIELD_WEIGHT = { name: 4, title: 2, description: 1 };
35
+ const FIELDS = Object.keys(FIELD_WEIGHT);
36
+ /** A tool's score for a query; zero means nothing matched. */
37
+ export function keywordScore(tool, query) {
38
+ // A query of only stopwords or one-letter words ("get") still finds by substring.
39
+ const raw = String(query ?? '').trim().toLowerCase();
40
+ const terms = queryTerms(query);
41
+ if (!terms.length && raw)
42
+ terms.push(raw);
43
+ if (!terms.length)
44
+ return 0;
45
+ const text = { name: tool.name ?? '', title: tool.title ?? '', description: tool.description ?? '' };
46
+ const split = Object.fromEntries(FIELDS.map((f) => [f, words(text[f])]));
47
+ const lowered = Object.fromEntries(FIELDS.map((f) => [f, text[f].toLowerCase()]));
48
+ let score = 0;
49
+ for (const term of terms) {
50
+ let best = 0;
51
+ for (const field of FIELDS) {
52
+ if (split[field].some((w) => w === term || (term.length >= 3 && w.startsWith(term))))
53
+ best = Math.max(best, FIELD_WEIGHT[field]);
54
+ else if (lowered[field].includes(term))
55
+ best = Math.max(best, FIELD_WEIGHT[field] / 2);
56
+ }
57
+ score += best;
58
+ }
59
+ if (score > 0 && split.name.join(' ').includes(terms.join(' ')))
60
+ score += 1;
61
+ return score;
62
+ }
63
+ /** The tools that match a query, best first (ties by name). An empty query lists every tool as given. */
64
+ export function searchTools(tools, query) {
65
+ if (!String(query ?? '').trim())
66
+ return tools;
67
+ return tools
68
+ .map((tool) => ({ tool, score: keywordScore(tool, query) }))
69
+ .filter((r) => r.score > 0)
70
+ .sort((a, b) => b.score - a.score || (a.tool.name < b.tool.name ? -1 : a.tool.name > b.tool.name ? 1 : 0))
71
+ .map((r) => r.tool);
72
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@almyty/mcp-server",
3
- "version": "1.5.8",
3
+ "version": "1.5.10",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -36,7 +36,7 @@
36
36
  "author": "almyty",
37
37
  "license": "Apache-2.0",
38
38
  "dependencies": {
39
- "@almyty/client": "^1.5.7",
39
+ "@almyty/client": "^1.5.10",
40
40
  "@modelcontextprotocol/server": "^2.3.0",
41
41
  "zod": "^4.6.6"
42
42
  },