@drsamonline/mcp 0.0.0-stage → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@drsamonline/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.12.3",
4
+ "description": "Model Context Protocol server: stdio and HTTP transports over the gateway.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js",
10
+ "./src/*": "./src/*"
11
+ },
12
+ "files": [
13
+ "src"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git://github.com/drsamonline/sui.git",
18
+ "directory": "packages/mcp"
19
+ },
20
+ "homepage": "https://github.com/drsamonline/sui#readme",
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ }
25
+ }
package/src/adapter.js ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * An MCP server as a provider adapter (B5.4).
3
+ *
4
+ * The contract is the same one every other adapter honours: take messages, return
5
+ * text plus usage. What makes this worth doing is that everything upstream —
6
+ * fallback, breakers, budgets, privacy tiers, canary, verification, the ledger —
7
+ * then applies to an MCP tool for free.
8
+ */
9
+
10
+ import { McpClient } from './client.js';
11
+
12
+ /** @type {Map<string, McpClient>} */
13
+ const clients = new Map();
14
+
15
+ /**
16
+ * @param {string} providerId
17
+ * @param {any} provider
18
+ * @param {NodeJS.ProcessEnv} [env]
19
+ */
20
+ export function mcpClientFor(providerId, provider, env = process.env) {
21
+ const key = `${providerId}:${provider.transport ?? (provider.url ? 'http' : 'stdio')}:${provider.url ?? provider.command}`;
22
+ let client = clients.get(key);
23
+ if (!client) {
24
+ client = new McpClient({
25
+ id: providerId,
26
+ transport: provider.transport ?? (provider.url ? 'http' : 'stdio'),
27
+ url: provider.url,
28
+ command: provider.command,
29
+ args: provider.args ?? [],
30
+ timeoutMs: provider.timeoutMs,
31
+ env,
32
+ });
33
+ clients.set(key, client);
34
+ }
35
+ return client;
36
+ }
37
+
38
+ /** Drop a cached client — used when a provider is edited or a test ends. */
39
+ export function resetMcpClients() {
40
+ for (const client of clients.values()) client.close().catch(() => {});
41
+ clients.clear();
42
+ }
43
+
44
+ /**
45
+ * Build the adapter. The tool name and the argument mapping come from the
46
+ * provider config, because only the operator knows what their tool expects.
47
+ *
48
+ * @param {string} providerId
49
+ * @param {any} provider
50
+ * @param {NodeJS.ProcessEnv} [env]
51
+ */
52
+ export function createMcpAdapter(providerId, provider, env = process.env) {
53
+ const tool = provider.tool;
54
+ if (!tool) {
55
+ throw new Error(`MCP provider "${providerId}" needs a tool name — which tool should answer a chat request?`);
56
+ }
57
+
58
+ return {
59
+ id: providerId,
60
+ type: 'mcp',
61
+ name: provider.label ?? providerId,
62
+ hasKey: true,
63
+
64
+ /**
65
+ * @param {{messages: Array<{role: string, content: string}>, max_tokens?: number}} req
66
+ */
67
+ async chat(req) {
68
+ const client = mcpClientFor(providerId, provider, env);
69
+ const messages = req.messages ?? [];
70
+ const prompt = messages.filter((m) => m.role === 'user').map((m) => m.content).join('\n\n');
71
+ const system = messages.filter((m) => m.role === 'system').map((m) => m.content).join('\n\n');
72
+
73
+ // `argument` lets an operator put the prompt under whatever key their tool
74
+ // wants; everything else is passed through as configured.
75
+ const args = { ...(provider.arguments ?? {}) };
76
+ args[provider.argument ?? 'prompt'] = prompt;
77
+ if (system && provider.systemArgument) args[provider.systemArgument] = system;
78
+ if (req.max_tokens && provider.maxTokensArgument) args[provider.maxTokensArgument] = req.max_tokens;
79
+
80
+ const result = await client.callTool(tool, args);
81
+ if (result.isError) {
82
+ // A tool error is a provider failure, with the tool's own words.
83
+ const error = new Error(result.text || `MCP tool "${tool}" reported an error.`);
84
+ /** @type {any} */ (error).status = 502;
85
+ throw error;
86
+ }
87
+
88
+ const text = result.text;
89
+ return {
90
+ text,
91
+ usage: {
92
+ // An MCP tool reports no tokens, so we estimate and say so in the docs.
93
+ prompt_tokens: Math.ceil(prompt.length / 4),
94
+ completion_tokens: Math.ceil(text.length / 4),
95
+ },
96
+ finishReason: 'stop',
97
+ raw: result.raw,
98
+ };
99
+ },
100
+ };
101
+ }
package/src/client.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * @drsamonline/mcp/client — Sui calling other MCP servers (B5.4).
3
+ *
4
+ * The other direction from `server.js`. An MCP server that exposes a tool is,
5
+ * from the gateway's point of view, another provider: it takes a prompt and
6
+ * returns text. So it becomes one — `type: "mcp"` — and every rule the router
7
+ * already enforces (breaker, budget, privacy tier, canary, verification) applies
8
+ * to it without a single special case.
9
+ *
10
+ * Two transports, matching the server side: `http` for a URL, `stdio` for a
11
+ * command the gateway launches.
12
+ */
13
+
14
+ import { spawn } from 'node:child_process';
15
+
16
+ const DEFAULT_TIMEOUT_MS = 30_000;
17
+
18
+ /**
19
+ * A minimal JSON-RPC client for one MCP server.
20
+ */
21
+ export class McpClient {
22
+ /**
23
+ * @param {{id: string, transport: 'http'|'stdio', url?: string, command?: string, args?: string[], env?: any, timeoutMs?: number, fetchImpl?: typeof fetch, now?: () => number}} opts
24
+ */
25
+ constructor(opts) {
26
+ this.id = opts.id;
27
+ this.transport = opts.transport ?? (opts.url ? 'http' : 'stdio');
28
+ this.url = opts.url;
29
+ this.command = opts.command;
30
+ this.args = opts.args ?? [];
31
+ this.env = opts.env ?? process.env;
32
+ this.timeoutMs = Number(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
33
+ this.fetchImpl = opts.fetchImpl ?? fetch;
34
+ this.now = opts.now ?? Date.now;
35
+
36
+ this.nextId = 1;
37
+ /** @type {Map<number, {resolve: Function, reject: Function, timer: any}>} */
38
+ this.pending = new Map();
39
+ this.child = null;
40
+ this.buffer = '';
41
+ this.ready = false;
42
+ this.serverInfo = null;
43
+ this.tools = [];
44
+ }
45
+
46
+ /** @param {{protocolVersion?: string}} [opts] */
47
+ async connect(opts = {}) {
48
+ if (this.ready) return this;
49
+
50
+ if (this.transport === 'stdio') {
51
+ if (!this.command) throw new Error(`MCP client "${this.id}" needs a command for the stdio transport.`);
52
+ this.child = spawn(this.command, this.args, { env: this.env, stdio: ['pipe', 'pipe', 'pipe'] });
53
+
54
+ this.child.stdout.setEncoding('utf8');
55
+ this.child.stdout.on('data', (chunk) => {
56
+ this.buffer += chunk;
57
+ let index;
58
+ while ((index = this.buffer.indexOf('\n')) !== -1) {
59
+ const line = this.buffer.slice(0, index).trim();
60
+ this.buffer = this.buffer.slice(index + 1);
61
+ if (line) this.#onMessage(line);
62
+ }
63
+ });
64
+ // stderr is logs, never protocol
65
+ this.child.stderr.setEncoding('utf8');
66
+ this.child.stderr.on('data', () => {});
67
+
68
+ this.child.on('exit', (code) => {
69
+ this.ready = false;
70
+ for (const [id, waiter] of this.pending) {
71
+ clearTimeout(waiter.timer);
72
+ waiter.reject(new Error(`MCP server "${this.id}" exited (code ${code}) before answering request ${id}.`));
73
+ }
74
+ this.pending.clear();
75
+ });
76
+ }
77
+
78
+ const init = await this.request('initialize', {
79
+ protocolVersion: opts.protocolVersion ?? '2024-11-05',
80
+ clientInfo: { name: 'sui', version: '0.1.0' },
81
+ capabilities: {},
82
+ });
83
+
84
+ this.serverInfo = init?.serverInfo ?? null;
85
+ this.ready = true;
86
+ this.notify('notifications/initialized');
87
+
88
+ const listed = await this.request('tools/list', {});
89
+ this.tools = listed?.tools ?? [];
90
+ return this;
91
+ }
92
+
93
+ /** @param {string} line */
94
+ #onMessage(line) {
95
+ let message;
96
+ try {
97
+ message = JSON.parse(line);
98
+ } catch {
99
+ return; // a non-JSON line is a log the peer should not have written; ignore it
100
+ }
101
+ if (message.id == null) return; // a notification from the server
102
+ const waiter = this.pending.get(message.id);
103
+ if (!waiter) return;
104
+ clearTimeout(waiter.timer);
105
+ this.pending.delete(message.id);
106
+ if (message.error) waiter.reject(Object.assign(new Error(message.error.message ?? 'MCP error'), { code: message.error.code }));
107
+ else waiter.resolve(message.result);
108
+ }
109
+
110
+ /**
111
+ * @param {string} method
112
+ * @param {any} params
113
+ */
114
+ async request(method, params) {
115
+ const id = this.nextId++;
116
+ const payload = { jsonrpc: '2.0', id, method, params };
117
+
118
+ if (this.transport === 'http') {
119
+ const controller = new AbortController();
120
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
121
+ try {
122
+ const res = await this.fetchImpl(this.url, {
123
+ method: 'POST',
124
+ headers: { 'content-type': 'application/json' },
125
+ body: JSON.stringify(payload),
126
+ signal: controller.signal,
127
+ });
128
+ if (!res.ok) throw new Error(`MCP server "${this.id}" answered ${res.status}.`);
129
+ const json = await res.json();
130
+ if (json.error) throw Object.assign(new Error(json.error.message ?? 'MCP error'), { code: json.error.code });
131
+ return json.result;
132
+ } finally {
133
+ clearTimeout(timer);
134
+ }
135
+ }
136
+
137
+ return new Promise((resolve, reject) => {
138
+ const timer = setTimeout(() => {
139
+ this.pending.delete(id);
140
+ reject(new Error(`MCP server "${this.id}" did not answer ${method} within ${this.timeoutMs}ms.`));
141
+ }, this.timeoutMs);
142
+ this.pending.set(id, { resolve, reject, timer });
143
+ this.child.stdin.write(`${JSON.stringify(payload)}\n`);
144
+ });
145
+ }
146
+
147
+ /** @param {string} method @param {any} [params] */
148
+ notify(method, params) {
149
+ const payload = { jsonrpc: '2.0', method, ...(params ? { params } : {}) };
150
+ if (this.transport === 'stdio' && this.child?.stdin?.writable) this.child.stdin.write(`${JSON.stringify(payload)}\n`);
151
+ return true;
152
+ }
153
+
154
+ /** @param {string} name @param {any} args */
155
+ async callTool(name, args) {
156
+ if (!this.ready) await this.connect();
157
+ const result = await this.request('tools/call', { name, arguments: args ?? {} });
158
+ const text = (result?.content ?? [])
159
+ .filter((block) => block?.type === 'text')
160
+ .map((block) => block.text)
161
+ .join('\n');
162
+ return { text, isError: Boolean(result?.isError), structured: result?.structuredContent ?? null, raw: result };
163
+ }
164
+
165
+ async close() {
166
+ this.ready = false;
167
+ for (const [, waiter] of this.pending) {
168
+ clearTimeout(waiter.timer);
169
+ waiter.reject(new Error(`MCP client "${this.id}" closed.`));
170
+ }
171
+ this.pending.clear();
172
+ if (this.child) {
173
+ this.child.stdin?.end();
174
+ this.child.kill();
175
+ this.child = null;
176
+ }
177
+ }
178
+ }
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @drsamonline/mcp — the Model Context Protocol server for Sui.
3
+ */
4
+
5
+ export { createMcpServer, SUPPORTED_PROTOCOL_VERSIONS, PROTOCOL_VERSION, ERROR_CODES, SERVER_NAME } from './server.js';
6
+ export { TOOLS, callTool } from './tools.js';
7
+ export { runStdio, createHttpHandler } from './transports.js';
8
+ export { McpClient } from './client.js';
9
+ export { createMcpAdapter, mcpClientFor, resetMcpClients } from './adapter.js';
package/src/server.js ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * @drsamonline/mcp — the Model Context Protocol server (B5.1, B5.2).
3
+ *
4
+ * An MCP server is a JSON-RPC 2.0 peer that advertises tools, resources and
5
+ * prompts. This one advertises the gateway: chat, models, explain, cost,
6
+ * compress and status. An agent that speaks MCP can use Sui without knowing it
7
+ * is a gateway at all.
8
+ *
9
+ * Two transports, one message handler:
10
+ * stdio newline-delimited JSON on stdin/stdout — what an editor launches
11
+ * http POST a JSON-RPC message, get JSON back — what a browser or a remote
12
+ * agent can reach
13
+ *
14
+ * Version handling is honest: we offer the revisions we implement and echo the
15
+ * client's choice when it is one of them. We do not claim a revision we have not
16
+ * written against.
17
+ */
18
+
19
+ import { TOOLS, callTool } from './tools.js';
20
+
21
+ /** Revisions this server implements. Ordered newest first. */
22
+ export const SUPPORTED_PROTOCOL_VERSIONS = ['2024-11-05'];
23
+ export const PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
24
+ export const SERVER_NAME = 'sui';
25
+
26
+ export const ERROR_CODES = {
27
+ parse: -32700,
28
+ invalidRequest: -32600,
29
+ methodNotFound: -32601,
30
+ invalidParams: -32602,
31
+ internal: -32603,
32
+ };
33
+
34
+ /**
35
+ * @param {{gateway: any, name?: string, version?: string, logger?: any}} opts
36
+ */
37
+ export function createMcpServer(opts) {
38
+ const gateway = opts.gateway;
39
+ const logger = opts.logger ?? { info() {}, warn() {} };
40
+ let initialised = false;
41
+
42
+ const ok = (id, result) => ({ jsonrpc: '2.0', id, result });
43
+ const fail = (id, code, message, data) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message, ...(data ? { data } : {}) } });
44
+
45
+ /**
46
+ * Handle one JSON-RPC message. Returns a response object, or null for a
47
+ * notification (which by definition has no reply).
48
+ *
49
+ * @param {any} message
50
+ */
51
+ async function handle(message) {
52
+ if (!message || typeof message !== 'object' || Array.isArray(message)) {
53
+ return fail(null, ERROR_CODES.invalidRequest, 'A JSON-RPC request must be a single object.');
54
+ }
55
+ const { id, method, params } = message;
56
+ const isNotification = id === undefined || id === null;
57
+
58
+ if (message.jsonrpc !== '2.0' || typeof method !== 'string') {
59
+ return fail(id ?? null, ERROR_CODES.invalidRequest, 'Not a JSON-RPC 2.0 request.');
60
+ }
61
+
62
+ try {
63
+ switch (method) {
64
+ case 'initialize': {
65
+ const requested = params?.protocolVersion;
66
+ const version = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : PROTOCOL_VERSION;
67
+ initialised = true;
68
+ return ok(id, {
69
+ protocolVersion: version,
70
+ capabilities: {
71
+ tools: { listChanged: false },
72
+ resources: { listChanged: false, subscribe: false },
73
+ prompts: { listChanged: false },
74
+ logging: {},
75
+ },
76
+ serverInfo: { name: opts.name ?? SERVER_NAME, version: opts.version ?? '0.1.0' },
77
+ instructions:
78
+ 'Sui is a model gateway. Call sui_chat to send a prompt through a combo (a virtual model); call sui_models first if you do not know the combo names. Every answer carries provenance: which provider answered, whether it was verified, and what it cost.',
79
+ });
80
+ }
81
+
82
+ case 'notifications/initialized':
83
+ return null;
84
+
85
+ case 'ping':
86
+ return ok(id, {});
87
+
88
+ case 'tools/list':
89
+ return ok(id, { tools: TOOLS });
90
+
91
+ case 'tools/call': {
92
+ const name = params?.name;
93
+ const args = params?.arguments ?? {};
94
+ if (!name) return fail(id, ERROR_CODES.invalidParams, 'tools/call needs a tool name.');
95
+ if (!TOOLS.some((t) => t.name === name)) {
96
+ return fail(id, ERROR_CODES.invalidParams, `No tool called "${name}". Available: ${TOOLS.map((t) => t.name).join(', ')}.`);
97
+ }
98
+ const result = await callTool(name, args, gateway);
99
+ return ok(id, result);
100
+ }
101
+
102
+ case 'resources/list':
103
+ return ok(id, { resources: [] });
104
+
105
+ case 'prompts/list':
106
+ return ok(id, { prompts: [] });
107
+
108
+ case 'shutdown':
109
+ return ok(id, {});
110
+
111
+ default:
112
+ if (isNotification) {
113
+ logger.warn?.(`ignoring unknown notification "${method}"`);
114
+ return null;
115
+ }
116
+ return fail(id, ERROR_CODES.methodNotFound, `Unknown method "${method}".`);
117
+ }
118
+ } catch (err) {
119
+ const message2 = /** @type {any} */ (err)?.message ?? String(err);
120
+ logger.warn?.(`mcp ${method} failed: ${message2}`);
121
+ return isNotification ? null : fail(id, ERROR_CODES.internal, message2);
122
+ }
123
+ }
124
+
125
+ return {
126
+ handle,
127
+ get initialised() {
128
+ return initialised;
129
+ },
130
+ /**
131
+ * Parse a line or body into a message, or into a ready-to-send error
132
+ * response. The key is `errorResponse`, not `error`: a full JSON-RPC envelope
133
+ * is what the transport writes, and naming it `error` made it read like a
134
+ * bare error object.
135
+ */
136
+ parse(text) {
137
+ try {
138
+ return { message: JSON.parse(text) };
139
+ } catch {
140
+ return { errorResponse: fail(null, ERROR_CODES.parse, 'That was not valid JSON.') };
141
+ }
142
+ },
143
+ };
144
+ }
package/src/tools.js ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The tools this MCP server advertises.
3
+ *
4
+ * Descriptions are written for a model to read: what it does, when to use it,
5
+ * and what it returns. Every tool returns MCP content blocks, and every result
6
+ * carries the provenance the gateway already produces — an agent should be able
7
+ * to say who answered without a second call.
8
+ */
9
+
10
+ const text = (value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }];
11
+
12
+ export const TOOLS = [
13
+ {
14
+ name: 'sui_chat',
15
+ description:
16
+ 'Send a prompt through the gateway and get an answer. Use a combo name (a virtual model such as "chat-default") or a model id. Returns the answer plus provenance: provider, model, whether the answer was verified, latency, and cost.',
17
+ inputSchema: {
18
+ type: 'object',
19
+ properties: {
20
+ prompt: { type: 'string', description: 'The user message.' },
21
+ combo: { type: 'string', description: 'Combo or model id. Defaults to the first combo in the config.' },
22
+ system: { type: 'string', description: 'Optional system instruction.' },
23
+ max_tokens: { type: 'integer', minimum: 1, description: 'Cap on the answer length.' },
24
+ privacy_tier: { type: 'string', enum: ['any', 'standard', 'strict'], description: 'How strict the provider policy must be.' },
25
+ region: { type: 'string', enum: ['any', 'eu', 'us', 'in', 'uk', 'apac'], description: 'Where the provider must process the data.' },
26
+ },
27
+ required: ['prompt'],
28
+ },
29
+ },
30
+ {
31
+ name: 'sui_models',
32
+ description:
33
+ 'List the combos (virtual models) this gateway answers to, their strategy, their targets, and which targets are currently reachable. Call this before sui_chat if you do not know the combo names.',
34
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
35
+ },
36
+ {
37
+ name: 'sui_explain',
38
+ description:
39
+ 'Explain why a route would go where it goes, without sending a request. Returns sentences naming the strategy, the order, and every target that was skipped and why.',
40
+ inputSchema: {
41
+ type: 'object',
42
+ properties: { combo: { type: 'string', description: 'The combo to explain. Defaults to the first combo.' } },
43
+ additionalProperties: false,
44
+ },
45
+ },
46
+ {
47
+ name: 'sui_cost',
48
+ description: 'Report what the gateway has spent today, broken down by provider and by combo, with the savings from cache hits and compression.',
49
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
50
+ },
51
+ {
52
+ name: 'sui_compress',
53
+ description:
54
+ 'Show what a compression preset would do to a prompt: the ratio, the engines that ran, and whether code, URLs and JSON survived. Useful before enabling compression for real traffic.',
55
+ inputSchema: {
56
+ type: 'object',
57
+ properties: {
58
+ text: { type: 'string', description: 'The prompt to compress.' },
59
+ preset: { type: 'string', enum: ['lite', 'standard', 'aggressive', 'ultra'], description: 'Defaults to standard.' },
60
+ },
61
+ required: ['text'],
62
+ },
63
+ },
64
+ {
65
+ name: 'sui_status',
66
+ description: 'Report gateway health: budget, pool health, breaker states, quota windows and the privacy posture of each provider.',
67
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
68
+ },
69
+ ];
70
+
71
+ /**
72
+ * @param {string} name
73
+ * @param {any} args
74
+ * @param {any} gateway
75
+ */
76
+ export async function callTool(name, args, gateway) {
77
+ const { router, config, ledger } = gateway;
78
+
79
+ switch (name) {
80
+ case 'sui_chat': {
81
+ const prompt = String(args?.prompt ?? '').trim();
82
+ if (!prompt) return { content: text('sui_chat needs a prompt.'), isError: true };
83
+
84
+ const combo = String(args.combo ?? Object.keys(config.combos)[0] ?? '');
85
+ const messages = [];
86
+ if (args.system) messages.push({ role: 'system', content: String(args.system) });
87
+ messages.push({ role: 'user', content: prompt });
88
+
89
+ try {
90
+ const result = await router.chat({
91
+ combo,
92
+ body: { messages, max_tokens: args.max_tokens },
93
+ privacyTier: args.privacy_tier,
94
+ region: args.region,
95
+ attribution: { user: 'mcp', tool: 'mcp-client' },
96
+ });
97
+ return {
98
+ content: text(result.text),
99
+ structuredContent: {
100
+ provider: result.meta.provider,
101
+ model: result.meta.modelId,
102
+ combo,
103
+ verified: result.meta.verified,
104
+ cached: result.meta.cached,
105
+ latencyMs: result.meta.latencyMs,
106
+ costUsd: result.meta.costUsd,
107
+ confidence: result.meta.verification?.confidence ?? null,
108
+ },
109
+ };
110
+ } catch (err) {
111
+ // A gateway failure is a tool error with the gateway's own sentence,
112
+ // which already names the fix.
113
+ return { content: text(/** @type {any} */ (err)?.message ?? String(err)), isError: true };
114
+ }
115
+ }
116
+
117
+ case 'sui_models': {
118
+ const combos = Object.entries(config.combos).map(([id, combo]) => {
119
+ const plan = router.plan(id, {});
120
+ return {
121
+ id,
122
+ label: combo.label ?? id,
123
+ strategy: combo.strategy,
124
+ reachable: plan.ordered.map((t) => t.modelId),
125
+ resting: plan.resting.map((t) => t.modelId),
126
+ skipped: plan.skipped.length,
127
+ };
128
+ });
129
+ return { content: text(combos), structuredContent: { combos } };
130
+ }
131
+
132
+ case 'sui_explain': {
133
+ const { explainPlan } = await import('@drsamonline/router');
134
+ const combo = String(args?.combo ?? Object.keys(config.combos)[0] ?? '');
135
+ const plan = router.plan(combo, {});
136
+ const lines = explainPlan(plan);
137
+ return { content: text(lines.join('\n')), structuredContent: { combo, lines } };
138
+ }
139
+
140
+ case 'sui_cost': {
141
+ const agg = ledger.aggregate({ since: 0 });
142
+ const summary = {
143
+ spentUsd: agg.totals.costUsd,
144
+ turns: agg.totals.turns,
145
+ failed: agg.totals.failed,
146
+ savedUsd: agg.totals.savings?.totalUsd ?? 0,
147
+ tokensSaved: agg.totals.savings?.tokensSaved ?? 0,
148
+ byProvider: Object.fromEntries(Object.entries(agg.byProvider).map(([k, v]) => [k, { turns: v.turns, costUsd: Math.round(v.costUsd * 1e6) / 1e6 }])),
149
+ byCombo: Object.fromEntries(Object.entries(agg.byCombo).map(([k, v]) => [k, { turns: v.turns, costUsd: Math.round(v.costUsd * 1e6) / 1e6 }])),
150
+ };
151
+ return { content: text(summary), structuredContent: summary };
152
+ }
153
+
154
+ case 'sui_compress': {
155
+ const { compress } = await import('@drsamonline/compression');
156
+ const body = String(args?.text ?? '');
157
+ if (!body.trim()) return { content: text('sui_compress needs some text.'), isError: true };
158
+ const result = compress(body, { preset: args?.preset ?? 'standard' });
159
+ const summary = {
160
+ preset: result.preset,
161
+ originalChars: result.originalChars,
162
+ compressedChars: result.compressedChars,
163
+ ratio: result.ratio,
164
+ skipped: result.skipped,
165
+ steps: result.steps,
166
+ text: result.text,
167
+ };
168
+ return { content: text(summary), structuredContent: summary };
169
+ }
170
+
171
+ case 'sui_status': {
172
+ const status = {
173
+ budget: { dailyUsd: config.budgets.dailyUsd, spentUsd: Math.round(ledger.todaySpendUsd() * 1e6) / 1e6 },
174
+ quotaWindows: router.quotaSnapshot?.() ?? [],
175
+ breakers: router.breaker.snapshot(),
176
+ privacy: {
177
+ defaultTier: config.privacy?.defaultTier ?? 'any',
178
+ region: config.privacy?.region ?? 'any',
179
+ providers: Object.entries(config.providers).map(([id, p]) => ({ id, retention: p.privacy?.retention ?? 'unknown', region: p.region ?? 'unknown' })),
180
+ },
181
+ };
182
+ return { content: text(status), structuredContent: status };
183
+ }
184
+
185
+ default:
186
+ return { content: text(`No tool called "${name}".`), isError: true };
187
+ }
188
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Two transports, one handler.
3
+ *
4
+ * stdio newline-delimited JSON-RPC on stdin/stdout. This is what an editor
5
+ * launches, and the framing is one JSON object per line — no headers,
6
+ * no length prefix. Anything written to stdout that is not a message
7
+ * breaks the peer, so logs go to stderr.
8
+ *
9
+ * http POST a JSON-RPC message, get JSON back. Stateless: every request
10
+ * carries everything needed to answer it.
11
+ */
12
+
13
+ import { createInterface } from 'node:readline';
14
+
15
+ /**
16
+ * Run the stdio loop until stdin closes.
17
+ *
18
+ * @param {{server: {handle: (m: any) => Promise<any>, parse: (t: string) => any}, stdin?: any, stdout?: any, stderr?: any, logger?: any}} opts
19
+ */
20
+ export function runStdio(opts) {
21
+ const input = opts.stdin ?? process.stdin;
22
+ const output = opts.stdout ?? process.stdout;
23
+ const errors = opts.stderr ?? process.stderr;
24
+ const logger = opts.logger ?? { info() {}, warn() {} };
25
+
26
+ const write = (message) => {
27
+ if (message) output.write(`${JSON.stringify(message)}\n`);
28
+ };
29
+
30
+ const rl = createInterface({ input, crlfDelay: Infinity });
31
+
32
+ // Answers go out in the order the messages arrived, including a parse error:
33
+ // a chain of promises is the simplest thing that cannot reorder.
34
+ let chain = Promise.resolve();
35
+
36
+ rl.on('line', (line) => {
37
+ const trimmed = line.trim();
38
+ if (!trimmed) return;
39
+
40
+ chain = chain.then(async () => {
41
+ const parsed = opts.server.parse(trimmed);
42
+ if (parsed.errorResponse) {
43
+ write(parsed.errorResponse);
44
+ return;
45
+ }
46
+ try {
47
+ write(await opts.server.handle(parsed.message));
48
+ } catch (err) {
49
+ errors.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: String(err?.message ?? err) } })}\n`);
50
+ logger.warn?.(`stdio handler failed: ${err?.message ?? err}`);
51
+ }
52
+ });
53
+ });
54
+
55
+ return new Promise((resolve) => {
56
+ rl.on('close', async () => {
57
+ await chain.catch(() => {});
58
+ resolve({ reason: 'stdin closed' });
59
+ });
60
+ });
61
+ }
62
+
63
+ /**
64
+ * A Node request handler for the HTTP transport.
65
+ *
66
+ * @param {{server: {handle: (m: any) => Promise<any>, parse: (t: string) => any}, path?: string, logger?: any}} opts
67
+ */
68
+ export function createHttpHandler(opts) {
69
+ const path = opts.path ?? '/mcp';
70
+ const logger = opts.logger ?? { info() {}, warn() {} };
71
+
72
+ return async function handleMcpHttp(req, res, url) {
73
+ if (url.pathname !== path) return false;
74
+
75
+ if (req.method === 'GET') {
76
+ // A streamable server may offer SSE here. This one answers a GET with the
77
+ // truth: it is POST-only, and says so instead of holding the socket open.
78
+ res.writeHead(405, { 'content-type': 'application/json', allow: 'POST' });
79
+ res.end(JSON.stringify({ error: 'This MCP endpoint is POST-only. Send JSON-RPC messages as the body.' }));
80
+ return true;
81
+ }
82
+
83
+ if (req.method !== 'POST') {
84
+ res.writeHead(405, { 'content-type': 'application/json', allow: 'POST' });
85
+ res.end(JSON.stringify({ error: 'Use POST.' }));
86
+ return true;
87
+ }
88
+
89
+ let raw = '';
90
+ for await (const chunk of req) raw += chunk;
91
+
92
+ const parsed = opts.server.parse(raw);
93
+ if (parsed.errorResponse) {
94
+ res.writeHead(400, { 'content-type': 'application/json' });
95
+ res.end(JSON.stringify(parsed.errorResponse));
96
+ return true;
97
+ }
98
+
99
+ try {
100
+ const response = await opts.server.handle(parsed.message);
101
+ if (!response) {
102
+ // A notification has no reply; 202 says "received" without inventing one.
103
+ res.writeHead(202);
104
+ res.end();
105
+ return true;
106
+ }
107
+ res.writeHead(200, { 'content-type': 'application/json' });
108
+ res.end(JSON.stringify(response));
109
+ } catch (err) {
110
+ logger.warn?.(`http mcp failed: ${err?.message ?? err}`);
111
+ res.writeHead(500, { 'content-type': 'application/json' });
112
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: String(err?.message ?? err) } }));
113
+ }
114
+ return true;
115
+ };
116
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.