@lifesi/genesis-mcp 0.0.0-stage → 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.
- package/bin/genesis-mcp.js +3 -0
- package/dist/hives-node-transport.d.ts +6 -0
- package/dist/hives-node-transport.js +145 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +11 -0
- package/dist/server.d.ts +45 -0
- package/dist/server.js +63 -0
- package/dist/tools.d.ts +70 -0
- package/dist/tools.js +117 -0
- package/package.json +18 -3
- package/README.md +0 -3
|
@@ -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/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { createServer, createHttpServer, serveStdio } from './server.js';
|
|
2
|
+
export { tools, specTools, metaTools, searchTools, callTool } from './tools.js';
|
|
3
|
+
export async function cli(args) {
|
|
4
|
+
const { serveStdio, createHttpServer } = await import('./server.js');
|
|
5
|
+
if (args[0] === 'http') {
|
|
6
|
+
const port = Number(process.env.PORT ?? args[1] ?? 8787);
|
|
7
|
+
createHttpServer().listen(port, () => console.error(`genesis-mcp listening on http://0.0.0.0:${port}/mcp`));
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
await serveStdio();
|
|
11
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import type { GenesisOptions } from '@lifesi/genesis';
|
|
4
|
+
export declare function createServer(opts?: GenesisOptions): Server<{
|
|
5
|
+
method: string;
|
|
6
|
+
params?: {
|
|
7
|
+
[x: string]: unknown;
|
|
8
|
+
_meta?: {
|
|
9
|
+
[x: string]: unknown;
|
|
10
|
+
progressToken?: string | number | undefined;
|
|
11
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
12
|
+
taskId: string;
|
|
13
|
+
} | undefined;
|
|
14
|
+
} | undefined;
|
|
15
|
+
} | undefined;
|
|
16
|
+
}, {
|
|
17
|
+
method: string;
|
|
18
|
+
params?: {
|
|
19
|
+
[x: string]: unknown;
|
|
20
|
+
_meta?: {
|
|
21
|
+
[x: string]: unknown;
|
|
22
|
+
progressToken?: string | number | undefined;
|
|
23
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
24
|
+
taskId: string;
|
|
25
|
+
} | undefined;
|
|
26
|
+
} | undefined;
|
|
27
|
+
} | undefined;
|
|
28
|
+
}, {
|
|
29
|
+
[x: string]: unknown;
|
|
30
|
+
_meta?: {
|
|
31
|
+
[x: string]: unknown;
|
|
32
|
+
progressToken?: string | number | undefined;
|
|
33
|
+
"io.modelcontextprotocol/related-task"?: {
|
|
34
|
+
taskId: string;
|
|
35
|
+
} | undefined;
|
|
36
|
+
} | undefined;
|
|
37
|
+
}>;
|
|
38
|
+
/** stdio: credential from GENESIS_API_KEY / GENESIS_TOKEN (or `credentials` provider). */
|
|
39
|
+
export declare function serveStdio(opts?: GenesisOptions): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Streamable HTTP (stateless) at POST /mcp, for mcp.life.one.
|
|
42
|
+
* Each request's `Authorization: Bearer <LifeID key | M2M token>` is forwarded as that caller's credential;
|
|
43
|
+
* the server never holds a credential of its own. Requests without one get 401 + WWW-Authenticate.
|
|
44
|
+
*/
|
|
45
|
+
export declare function createHttpServer(opts?: Omit<GenesisOptions, 'apiKey' | 'token' | 'credentials'>): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
4
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import { callTool, tools } from './tools.js';
|
|
7
|
+
export function createServer(opts = {}) {
|
|
8
|
+
const server = new Server({ name: 'genesis', version: '0.1.1' }, {
|
|
9
|
+
capabilities: { tools: {} },
|
|
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
|
+
});
|
|
12
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools() }));
|
|
13
|
+
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => callTool(opts, req.params.name, (req.params.arguments ?? {}), extra.signal));
|
|
14
|
+
return server;
|
|
15
|
+
}
|
|
16
|
+
/** stdio: credential from GENESIS_API_KEY / GENESIS_TOKEN (or `credentials` provider). */
|
|
17
|
+
export async function serveStdio(opts = {}) {
|
|
18
|
+
await createServer(opts).connect(new StdioServerTransport());
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Streamable HTTP (stateless) at POST /mcp, for mcp.life.one.
|
|
22
|
+
* Each request's `Authorization: Bearer <LifeID key | M2M token>` is forwarded as that caller's credential;
|
|
23
|
+
* the server never holds a credential of its own. Requests without one get 401 + WWW-Authenticate.
|
|
24
|
+
*/
|
|
25
|
+
export function createHttpServer(opts = {}) {
|
|
26
|
+
return http.createServer(async (req, res) => {
|
|
27
|
+
const url = new URL(req.url ?? '/', 'http://x');
|
|
28
|
+
if (url.pathname === '/healthz') {
|
|
29
|
+
res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (url.pathname !== '/mcp') {
|
|
33
|
+
res.writeHead(404).end();
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (req.method !== 'POST') {
|
|
37
|
+
res.writeHead(405, { allow: 'POST' }).end();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization ?? '');
|
|
41
|
+
if (!m) {
|
|
42
|
+
res.writeHead(401, { 'content-type': 'application/json', 'www-authenticate': 'Bearer realm="genesis", error="invalid_token"' })
|
|
43
|
+
.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32001, message: 'Send Authorization: Bearer <LifeID API key or M2M token>' }, id: null }));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
let body = '';
|
|
47
|
+
for await (const chunk of req)
|
|
48
|
+
body += chunk;
|
|
49
|
+
let parsed;
|
|
50
|
+
try {
|
|
51
|
+
parsed = JSON.parse(body);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
res.writeHead(400).end('invalid JSON');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const server = createServer({ ...opts, token: m[1] });
|
|
58
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
59
|
+
res.on('close', () => { transport.close(); server.close(); });
|
|
60
|
+
await server.connect(transport);
|
|
61
|
+
await transport.handleRequest(req, res, parsed);
|
|
62
|
+
});
|
|
63
|
+
}
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type GenesisOptions, type OperationMeta } from '@lifesi/genesis';
|
|
2
|
+
export interface ToolDef {
|
|
3
|
+
name: string;
|
|
4
|
+
title?: string;
|
|
5
|
+
description: string;
|
|
6
|
+
inputSchema: Record<string, unknown>;
|
|
7
|
+
annotations?: {
|
|
8
|
+
readOnlyHint?: boolean;
|
|
9
|
+
destructiveHint?: boolean;
|
|
10
|
+
idempotentHint?: boolean;
|
|
11
|
+
openWorldHint?: boolean;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** Operations callable by agents (everything except gateway-internal ones like credential verify). */
|
|
15
|
+
export declare const callable: [string, OperationMeta][];
|
|
16
|
+
/** Curated tools: one per operation tagged x-mcp in the merged spec. */
|
|
17
|
+
export declare const specTools: ToolDef[];
|
|
18
|
+
export declare const metaTools: ToolDef[];
|
|
19
|
+
export declare const tools: () => ToolDef[];
|
|
20
|
+
export declare function searchTools(query: string, service?: string, limit?: number): {
|
|
21
|
+
operation: string;
|
|
22
|
+
service: string;
|
|
23
|
+
method: string;
|
|
24
|
+
path: string;
|
|
25
|
+
summary: string;
|
|
26
|
+
status: string;
|
|
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
|
+
};
|
|
60
|
+
}[];
|
|
61
|
+
type Result = {
|
|
62
|
+
content: {
|
|
63
|
+
type: 'text';
|
|
64
|
+
text: string;
|
|
65
|
+
}[];
|
|
66
|
+
isError?: boolean;
|
|
67
|
+
structuredContent?: Record<string, unknown>;
|
|
68
|
+
};
|
|
69
|
+
export declare function callTool(opts: GenesisOptions, name: string, args?: Record<string, unknown>, signal?: AbortSignal): Promise<Result>;
|
|
70
|
+
export {};
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
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;
|
|
10
|
+
const all = Object.entries(operationTable);
|
|
11
|
+
/** Operations callable by agents (everything except gateway-internal ones like credential verify). */
|
|
12
|
+
export const callable = all.filter(([, op]) => !op.internal);
|
|
13
|
+
function describe(id, op) {
|
|
14
|
+
const status = op.upstream.status === 'live' ? '' : ` [service status: ${op.upstream.status}]`;
|
|
15
|
+
return `${op.summary} (${op.method} ${op.path})${status}`;
|
|
16
|
+
}
|
|
17
|
+
const annotate = (op) => ({
|
|
18
|
+
readOnlyHint: op.method === 'GET', destructiveHint: op.method === 'DELETE',
|
|
19
|
+
idempotentHint: ['GET', 'PUT', 'DELETE'].includes(op.method), openWorldHint: true,
|
|
20
|
+
});
|
|
21
|
+
/** Curated tools: one per operation tagged x-mcp in the merged spec. */
|
|
22
|
+
export const specTools = callable.filter(([, op]) => op.mcp).map(([id, op]) => ({
|
|
23
|
+
name: id, title: op.summary, description: describe(id, op), inputSchema: inputSchema(id, op), annotations: annotate(op),
|
|
24
|
+
}));
|
|
25
|
+
export const metaTools = [
|
|
26
|
+
{
|
|
27
|
+
name: 'genesis_search_tools',
|
|
28
|
+
description: `Search all ${callable.length} Genesis API operations (Foundry, Hives, Relays, IAM...) by keyword. Returns operation ids and input schemas to use with genesis_call.`,
|
|
29
|
+
inputSchema: { type: 'object', properties: {
|
|
30
|
+
query: { type: 'string', description: 'keywords, e.g. "dns record" or "deploy"' },
|
|
31
|
+
service: { type: 'string', description: 'optional service filter: foundry | hives | relays | iam' },
|
|
32
|
+
limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
|
|
33
|
+
}, required: ['query'], additionalProperties: false },
|
|
34
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'genesis_call',
|
|
38
|
+
description: 'Call any Genesis API operation by id (find ids with genesis_search_tools). arguments = path params + query params + body.',
|
|
39
|
+
inputSchema: { type: 'object', properties: {
|
|
40
|
+
operation: { type: 'string', description: 'operation id, e.g. hives_list_secrets' },
|
|
41
|
+
arguments: { type: 'object', additionalProperties: true, default: {} },
|
|
42
|
+
}, required: ['operation'], additionalProperties: false },
|
|
43
|
+
annotations: { openWorldHint: true },
|
|
44
|
+
},
|
|
45
|
+
];
|
|
46
|
+
export const tools = () => [...metaTools, ...specTools];
|
|
47
|
+
export function searchTools(query, service, limit = 10) {
|
|
48
|
+
const terms = query.toLowerCase().split(/\W+/).filter(Boolean);
|
|
49
|
+
return callable
|
|
50
|
+
.filter(([, op]) => !service || op.service === service)
|
|
51
|
+
.map(([id, op]) => {
|
|
52
|
+
const hay = `${id} ${op.summary} ${op.path}`.toLowerCase();
|
|
53
|
+
const score = terms.reduce((s, t) => s + (hay.includes(t) ? (id.toLowerCase().includes(t) ? 2 : 1) : 0), 0);
|
|
54
|
+
return { id, op, score };
|
|
55
|
+
})
|
|
56
|
+
.filter((x) => x.score > 0)
|
|
57
|
+
.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id))
|
|
58
|
+
.slice(0, limit)
|
|
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) }));
|
|
60
|
+
}
|
|
61
|
+
const text = (v, isError = false) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }], ...(isError ? { isError } : {}) });
|
|
62
|
+
async function invoke(genesis, id, args, signal) {
|
|
63
|
+
const op = operationTable[id];
|
|
64
|
+
if (!op || op.internal)
|
|
65
|
+
return text(`Unknown operation "${id}". Use genesis_search_tools to find one.`, true);
|
|
66
|
+
try {
|
|
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);
|
|
96
|
+
return text(r === undefined ? { ok: true } : r);
|
|
97
|
+
}
|
|
98
|
+
catch (e) {
|
|
99
|
+
if (e instanceof GenesisError)
|
|
100
|
+
return text({ error: { type: e.type, status: e.status, message: e.message, request_id: e.requestId } }, true);
|
|
101
|
+
return text({ error: { type: 'network', message: e.message, hint: `The ${op.service} service may be unreachable (status: ${op.upstream.status}).` } }, true);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
export async function callTool(opts, name, args = {}, signal) {
|
|
105
|
+
if (name === 'genesis_search_tools')
|
|
106
|
+
return text(searchTools(String(args.query ?? ''), args.service, Number(args.limit ?? 10)));
|
|
107
|
+
if (name !== 'genesis_call' && !specTools.some((t) => t.name === name))
|
|
108
|
+
return text(`Unknown tool "${name}".`, true);
|
|
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);
|
|
117
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lifesi/genesis-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Genesis MCP server (stdio + streamable HTTP): tools generated from the Genesis OpenAPI",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"genesis-mcp": "bin/genesis-mcp.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"dist"
|
|
12
|
+
],
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
15
|
+
"undici": "6.29.0",
|
|
16
|
+
"@lifesi/genesis": "0.1.1"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.json"
|
|
20
|
+
}
|
|
6
21
|
}
|
package/README.md
DELETED