@lifesi/genesis-mcp 0.1.0 → 0.1.1

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.
@@ -0,0 +1,6 @@
1
+ import { type GenesisOptions } from '@lifesi/genesis';
2
+ export declare function closeHivesNodeTransport(): Promise<void>;
3
+ export declare function hivesOperationBudget(id: string): number;
4
+ /** Hives leaf transport. Caller fetch overrides stay authoritative; only native
5
+ * global fetch gets our Agent. Every operation retains an overall body deadline. */
6
+ export declare function createHivesNodeTransport(opts: GenesisOptions, callerSignal?: AbortSignal): typeof fetch;
@@ -0,0 +1,145 @@
1
+ import { Agent } from 'undici';
2
+ import { Genesis, operationTable } from '@lifesi/genesis';
3
+ // Node's native fetch accepts a compatible per-request dispatcher. Never change
4
+ // the global dispatcher or the portable SDK: other products retain their transport.
5
+ const agentOptions = { headersTimeout: 340_000, bodyTimeout: 340_000, connect: { timeout: 5_000 }, connections: 4, pipelining: 1 };
6
+ let agent;
7
+ const nativeAgent = () => agent ??= new Agent(agentOptions);
8
+ export async function closeHivesNodeTransport() {
9
+ const current = agent;
10
+ agent = undefined;
11
+ await current?.destroy();
12
+ }
13
+ export function hivesOperationBudget(id) {
14
+ if (id === 'hives_cancel_deployment' || id === 'hives_delete_deployment')
15
+ return 330_000;
16
+ if (['hives_create_deployment', 'hives_upload_deployment', 'hives_invoke_deployment', 'hives_invoke_function', 'hives_invoke_function_async'].includes(id))
17
+ return 40_000;
18
+ if (['hives_create_function', 'hives_update_function', 'hives_delete_function'].includes(id))
19
+ return 100_000;
20
+ return 20_000;
21
+ }
22
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
23
+ const templatePattern = (value) => new RegExp('^' + value.split(/(\{[^}]+\})/).map((part) => part.startsWith('{') ? '[^/]+' : escape(part)).join('') + '$');
24
+ /** Hives leaf transport. Caller fetch overrides stay authoritative; only native
25
+ * global fetch gets our Agent. Every operation retains an overall body deadline. */
26
+ export function createHivesNodeTransport(opts, callerSignal) {
27
+ const supplied = opts.fetch ?? globalThis.fetch;
28
+ const underlying = supplied.bind(globalThis);
29
+ const useNative = supplied === globalThis.fetch;
30
+ const resolver = new Genesis(opts);
31
+ const routes = Object.entries(operationTable)
32
+ .filter(([, op]) => op.service === 'hives' && !op.internal)
33
+ .flatMap(([id, op]) => {
34
+ const direct = resolver.routing === 'direct';
35
+ let base;
36
+ try {
37
+ base = new URL(direct ? (opts.upstreams?.hives ?? op.upstream.base) : resolver.baseUrl);
38
+ }
39
+ catch {
40
+ throw new Error('Invalid Hives service address.');
41
+ }
42
+ const path = direct ? op.upstream.path : op.path;
43
+ const prefix = base.pathname.replace(/\/+$/, '');
44
+ const paths = [path];
45
+ if (!direct && path.startsWith('/v1/hives/'))
46
+ paths.push(path.replace('/v1/hives/', '/hives/v1/'));
47
+ return paths.map((p) => ({ id, origin: base.origin, method: direct ? op.upstream.method : op.method, pattern: templatePattern(prefix + p) }));
48
+ });
49
+ return (async (input, init = {}) => {
50
+ let url;
51
+ try {
52
+ url = new URL(input instanceof Request ? input.url : String(input));
53
+ }
54
+ catch {
55
+ throw new Error('Invalid Hives request address.');
56
+ }
57
+ const method = (init.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
58
+ const route = routes.find((entry) => entry.origin === url.origin && entry.method === method && entry.pattern.test(url.pathname));
59
+ if (!route)
60
+ return underlying(input, init);
61
+ const controller = new AbortController();
62
+ let message = 'Hives transport failed. Refresh the resource and retry.';
63
+ const safeError = () => new Error(message);
64
+ const signals = [...new Set([callerSignal, init.signal, input instanceof Request ? input.signal : undefined].filter((signal) => !!signal))];
65
+ const canceled = () => {
66
+ message = 'Hives request canceled before completion. Refresh the resource before retrying.';
67
+ controller.abort();
68
+ };
69
+ for (const signal of signals)
70
+ signal.addEventListener('abort', canceled, { once: true });
71
+ const timer = setTimeout(() => {
72
+ message = 'Hives request deadline exceeded. Refresh the resource before retrying.';
73
+ controller.abort();
74
+ }, hivesOperationBudget(route.id));
75
+ timer.unref();
76
+ let abortReject = () => { };
77
+ let reader;
78
+ let bodyController;
79
+ const aborted = () => {
80
+ abortReject(safeError());
81
+ bodyController?.error(safeError());
82
+ void reader?.cancel().catch(() => { });
83
+ cleanup();
84
+ };
85
+ controller.signal.addEventListener('abort', aborted, { once: true });
86
+ const abortPromise = new Promise((_, reject) => { abortReject = reject; });
87
+ void abortPromise.catch(() => { });
88
+ const cleanup = () => {
89
+ clearTimeout(timer);
90
+ for (const signal of signals)
91
+ signal.removeEventListener('abort', canceled);
92
+ controller.signal.removeEventListener('abort', aborted);
93
+ };
94
+ if (signals.some((signal) => signal.aborted))
95
+ canceled();
96
+ try {
97
+ if (controller.signal.aborted)
98
+ throw safeError();
99
+ const requestInit = {
100
+ ...init, signal: controller.signal, cache: 'no-store',
101
+ redirect: init.redirect === 'manual' ? 'manual' : 'error',
102
+ ...(useNative ? { dispatcher: nativeAgent() } : {}),
103
+ };
104
+ const pending = underlying(input, requestInit);
105
+ // A caller transport may ignore AbortSignal. Reject on our budget anyway,
106
+ // and discard any late response rather than presenting an acknowledgement.
107
+ void pending.then((response) => { if (controller.signal.aborted)
108
+ void response.body?.cancel().catch(() => { }); }, () => { });
109
+ const response = await Promise.race([pending, abortPromise]);
110
+ if (controller.signal.aborted)
111
+ throw safeError();
112
+ if (!response.body) {
113
+ cleanup();
114
+ return response;
115
+ }
116
+ reader = response.body.getReader();
117
+ const body = new ReadableStream({
118
+ start(value) { bodyController = value; },
119
+ async pull(value) {
120
+ try {
121
+ const next = await reader.read();
122
+ if (controller.signal.aborted)
123
+ return;
124
+ if (next.done) {
125
+ cleanup();
126
+ value.close();
127
+ }
128
+ else
129
+ value.enqueue(next.value);
130
+ }
131
+ catch {
132
+ cleanup();
133
+ value.error(safeError());
134
+ }
135
+ },
136
+ async cancel() { cleanup(); await reader.cancel().catch(() => { }); },
137
+ });
138
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
139
+ }
140
+ catch {
141
+ cleanup();
142
+ throw safeError();
143
+ }
144
+ });
145
+ }
package/dist/server.js CHANGED
@@ -5,12 +5,12 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprot
5
5
  import http from 'node:http';
6
6
  import { callTool, tools } from './tools.js';
7
7
  export function createServer(opts = {}) {
8
- const server = new Server({ name: 'genesis', version: '0.1.0' }, {
8
+ const server = new Server({ name: 'genesis', version: '0.1.1' }, {
9
9
  capabilities: { tools: {} },
10
10
  instructions: 'Genesis: one API for Foundry (inference), Hives (compute), Relays (DNS) and LifeID keys. Use the named tools for common tasks; use genesis_search_tools + genesis_call for anything else.',
11
11
  });
12
12
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools() }));
13
- server.setRequestHandler(CallToolRequestSchema, async (req) => callTool(opts, req.params.name, (req.params.arguments ?? {})));
13
+ server.setRequestHandler(CallToolRequestSchema, async (req, extra) => callTool(opts, req.params.name, (req.params.arguments ?? {}), extra.signal));
14
14
  return server;
15
15
  }
16
16
  /** stdio: credential from GENESIS_API_KEY / GENESIS_TOKEN (or `credentials` provider). */
package/dist/tools.d.ts CHANGED
@@ -24,7 +24,39 @@ export declare function searchTools(query: string, service?: string, limit?: num
24
24
  path: string;
25
25
  summary: string;
26
26
  status: string;
27
- inputSchema: Record<string, unknown>;
27
+ inputSchema: Record<string, unknown> | {
28
+ type: string;
29
+ properties: {
30
+ project_id: {
31
+ type: string;
32
+ description: string;
33
+ };
34
+ wasm_base64: {
35
+ type: string;
36
+ maxLength: number;
37
+ description: string;
38
+ };
39
+ filename: {
40
+ type: string;
41
+ maxLength: number;
42
+ };
43
+ git_sha: {
44
+ type: string;
45
+ minLength: number;
46
+ maxLength: number;
47
+ };
48
+ git_branch: {
49
+ type: string;
50
+ maxLength: number;
51
+ };
52
+ git_message: {
53
+ type: string;
54
+ maxLength: number;
55
+ };
56
+ };
57
+ required: string[];
58
+ additionalProperties: boolean;
59
+ };
28
60
  }[];
29
61
  type Result = {
30
62
  content: {
@@ -34,5 +66,5 @@ type Result = {
34
66
  isError?: boolean;
35
67
  structuredContent?: Record<string, unknown>;
36
68
  };
37
- export declare function callTool(opts: GenesisOptions, name: string, args?: Record<string, unknown>): Promise<Result>;
69
+ export declare function callTool(opts: GenesisOptions, name: string, args?: Record<string, unknown>, signal?: AbortSignal): Promise<Result>;
38
70
  export {};
package/dist/tools.js CHANGED
@@ -1,4 +1,12 @@
1
- import { Genesis, GenesisError, operationTable } from '@lifesi/genesis';
1
+ import { createHivesNodeTransport } from './hives-node-transport.js';
2
+ import { Genesis, GenesisError, MAX_WASM_BYTES, hivesResponseBytes, operationTable } from '@lifesi/genesis';
3
+ const uploadSchema = { type: 'object', properties: {
4
+ project_id: { type: 'string', description: 'Project owned by the caller’s verified org' },
5
+ wasm_base64: { type: 'string', maxLength: Math.ceil(MAX_WASM_BYTES / 3) * 4, description: 'Explicit standard-base64 content of a real WASM binary (decoded maximum 10 MiB)' },
6
+ filename: { type: 'string', maxLength: 255 },
7
+ git_sha: { type: 'string', minLength: 7, maxLength: 40 }, git_branch: { type: 'string', maxLength: 255 }, git_message: { type: 'string', maxLength: 1000 },
8
+ }, required: ['project_id', 'wasm_base64'], additionalProperties: false };
9
+ const inputSchema = (id, op) => id === 'hives_upload_deployment' ? uploadSchema : op.inputSchema;
2
10
  const all = Object.entries(operationTable);
3
11
  /** Operations callable by agents (everything except gateway-internal ones like credential verify). */
4
12
  export const callable = all.filter(([, op]) => !op.internal);
@@ -12,7 +20,7 @@ const annotate = (op) => ({
12
20
  });
13
21
  /** Curated tools: one per operation tagged x-mcp in the merged spec. */
14
22
  export const specTools = callable.filter(([, op]) => op.mcp).map(([id, op]) => ({
15
- name: id, title: op.summary, description: describe(id, op), inputSchema: op.inputSchema, annotations: annotate(op),
23
+ name: id, title: op.summary, description: describe(id, op), inputSchema: inputSchema(id, op), annotations: annotate(op),
16
24
  }));
17
25
  export const metaTools = [
18
26
  {
@@ -48,15 +56,43 @@ export function searchTools(query, service, limit = 10) {
48
56
  .filter((x) => x.score > 0)
49
57
  .sort((a, b) => b.score - a.score || a.id.localeCompare(b.id))
50
58
  .slice(0, limit)
51
- .map(({ id, op }) => ({ operation: id, service: op.service, method: op.method, path: op.path, summary: op.summary, status: op.upstream.status, inputSchema: op.inputSchema }));
59
+ .map(({ id, op }) => ({ operation: id, service: op.service, method: op.method, path: op.path, summary: op.summary, status: op.upstream.status, inputSchema: inputSchema(id, op) }));
52
60
  }
53
61
  const text = (v, isError = false) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }], ...(isError ? { isError } : {}) });
54
- async function invoke(genesis, id, args) {
62
+ async function invoke(genesis, id, args, signal) {
55
63
  const op = operationTable[id];
56
64
  if (!op || op.internal)
57
65
  return text(`Unknown operation "${id}". Use genesis_search_tools to find one.`, true);
58
66
  try {
59
- const r = await genesis.request(id, args);
67
+ let r;
68
+ if (op.service === 'hives' && op.rawResponse) {
69
+ const response = await genesis.raw(id, args, { signal });
70
+ const bytes = await hivesResponseBytes(response);
71
+ const payload = { status: response.status, headers: Object.fromEntries(response.headers), body_base64: Buffer.from(bytes).toString('base64') };
72
+ return { ...text(payload), structuredContent: payload };
73
+ }
74
+ else if (id === 'hives_upload_deployment') {
75
+ const encoded = args.wasm_base64;
76
+ if (typeof args.project_id !== 'string' || !args.project_id || typeof encoded !== 'string'
77
+ || encoded.length > Math.ceil(MAX_WASM_BYTES / 3) * 4 || encoded.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) {
78
+ return text({ error: { type: 'invalid_request', message: 'Provide a project ID and standard base64 of a real WASM file, up to 10 MiB decoded.' } }, true);
79
+ }
80
+ const bytes = Buffer.from(encoded, 'base64');
81
+ if (bytes.toString('base64') !== encoded || bytes.length > MAX_WASM_BYTES)
82
+ return text({ error: { type: 'invalid_request', message: 'WASM base64 is invalid or exceeds 10 MiB.' } }, true);
83
+ const optional = (key) => {
84
+ if (args[key] !== undefined && typeof args[key] !== 'string')
85
+ throw new Error('WASM upload metadata must contain strings.');
86
+ return args[key];
87
+ };
88
+ r = await genesis.hives.deployments.upload(args.project_id, new Blob([Uint8Array.from(bytes)], { type: 'application/wasm' }), {
89
+ filename: optional('filename'), git_sha: optional('git_sha'), git_branch: optional('git_branch'), git_message: optional('git_message'),
90
+ });
91
+ }
92
+ else
93
+ r = op.service === 'hives'
94
+ ? await genesis.request(id, args, { signal })
95
+ : await genesis.request(id, args);
60
96
  return text(r === undefined ? { ok: true } : r);
61
97
  }
62
98
  catch (e) {
@@ -65,13 +101,17 @@ async function invoke(genesis, id, args) {
65
101
  return text({ error: { type: 'network', message: e.message, hint: `The ${op.service} service may be unreachable (status: ${op.upstream.status}).` } }, true);
66
102
  }
67
103
  }
68
- export async function callTool(opts, name, args = {}) {
104
+ export async function callTool(opts, name, args = {}, signal) {
69
105
  if (name === 'genesis_search_tools')
70
106
  return text(searchTools(String(args.query ?? ''), args.service, Number(args.limit ?? 10)));
71
- const genesis = new Genesis(opts);
72
- if (name === 'genesis_call')
73
- return invoke(genesis, String(args.operation ?? ''), args.arguments ?? {});
74
- if (!specTools.some((t) => t.name === name))
107
+ if (name !== 'genesis_call' && !specTools.some((t) => t.name === name))
75
108
  return text(`Unknown tool "${name}".`, true);
76
- return invoke(genesis, name, args);
109
+ const id = name === 'genesis_call' ? String(args.operation ?? '') : name;
110
+ const input = name === 'genesis_call' ? args.arguments ?? {} : args;
111
+ const op = operationTable[id];
112
+ if (!op || op.internal)
113
+ return text(`Unknown operation "${id}". Use genesis_search_tools to find one.`, true);
114
+ const hives = op.service === 'hives';
115
+ const genesis = new Genesis(hives ? { ...opts, fetch: createHivesNodeTransport(opts, signal) } : opts);
116
+ return invoke(genesis, id, input, hives ? signal : undefined);
77
117
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifesi/genesis-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Genesis MCP server (stdio + streamable HTTP): tools generated from the Genesis OpenAPI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,7 +12,8 @@
12
12
  ],
13
13
  "dependencies": {
14
14
  "@modelcontextprotocol/sdk": "^1.32.1",
15
- "@lifesi/genesis": "0.1.0"
15
+ "undici": "6.29.0",
16
+ "@lifesi/genesis": "0.1.1"
16
17
  },
17
18
  "scripts": {
18
19
  "build": "tsc -p tsconfig.json"