@x12i/kinedrop-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.
Files changed (3) hide show
  1. package/index.mjs +368 -0
  2. package/package.json +11 -4
  3. package/README.md +0 -3
package/index.mjs ADDED
@@ -0,0 +1,368 @@
1
+ #!/usr/bin/env node
2
+ import { createInterface } from 'node:readline';
3
+ import { pathToFileURL } from 'node:url';
4
+ const { KineDropClient,keyroxClientOptionsFromEnv,isReadOnlyRequest,APPS_OPERATIONS,APPS_MCP_TOOLS,SERVICE_OPERATIONS,SERVICE_MCP_TOOLS,PLACEMENT_OPERATIONS,PLACEMENT_MCP_TOOLS,validateServiceInput } = await import('@x12i/kinedrop').catch(error => {
5
+ if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
6
+ return import('../kinedrop-sdk/index.mjs');
7
+ });
8
+
9
+ const identifier = { type: 'string', minLength: 1, maxLength: 512 };
10
+ const idempotency = { type: 'string', minLength: 8, maxLength: 128, pattern: '^[A-Za-z0-9_.-]{8,128}$' };
11
+ const object = (properties, required = []) => ({ type: 'object', properties, additionalProperties: false, ...(required.length ? { required } : {}) });
12
+ const enumeration = (...values) => ({ type: 'string', enum: values });
13
+ const arbitraryObject = { type: 'object', additionalProperties: true };
14
+ const blueprintSchema = object({
15
+ name: identifier,
16
+ resources: { type: 'array', maxItems: 100, items: { type: 'object', properties: { id: identifier, name: identifier, service: identifier, dependsOn: { type: 'array', items: identifier, maxItems: 100 } }, required: ['id', 'service'], additionalProperties: true } },
17
+ }, ['name', 'resources']);
18
+
19
+ export const MCP_TOOLS = Object.freeze([
20
+ {
21
+ name: 'kinedrop_discover',
22
+ description: 'Discover the service catalogue and declared capabilities. Native engine readiness is reported explicitly; discovery does not provision anything.',
23
+ inputSchema: object({ service: identifier }),
24
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
25
+ },
26
+ {
27
+ name: 'kinedrop_workspace_enrollment',
28
+ description: 'Plan, apply, or inspect a customer workspace enrollment, or inventory the selected workspace app targets and managed service bindings. Plan and apply require workspaces:provision. Responses omit secrets.',
29
+ inputSchema: object({
30
+ action: enumeration('plan', 'apply', 'inspect', 'inventory'),
31
+ operationId: identifier,
32
+ request: arbitraryObject,
33
+ }, ['action']),
34
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
35
+ },
36
+ {
37
+ name: 'kinedrop_inventory_and_health',
38
+ description: 'Read actual control-plane health, organizations and optional resources for the configured organization.',
39
+ inputSchema: object({ includeResources: { type: 'boolean' } }),
40
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
41
+ },
42
+ {
43
+ name: 'kinedrop_apply_blueprint',
44
+ description: 'Plan a stack dependency graph, or register a previously planned stack. Apply prepares local resource intent; it never deploys a cluster or claims native engines are running.',
45
+ inputSchema: object({ action: enumeration('plan', 'apply'), blueprint: blueprintSchema, planId: identifier, idempotencyKey: idempotency, dryRun: { type: 'boolean' } }, ['action']),
46
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
47
+ },
48
+ {
49
+ name: 'kinedrop_ground_and_extract_document',
50
+ description: 'Ground text or uploaded file bytes with UTF-16 source spans and redaction; inspect bundles or resolve spans. PDF/Office requires published readers. OCR/model extraction requires separately configured integrations.',
51
+ inputSchema: object({
52
+ action: enumeration('ingest', 'list', 'get', 'resolveSpan', 'extract'),
53
+ text: { type: 'string', maxLength: 2_097_152 }, contentBase64: {type:'string',maxLength:1_398_104}, fileName: { type: 'string', maxLength: 255 },
54
+ onSecret: enumeration('redact', 'fail'), documentId: identifier,
55
+ startChar: { type: 'integer', minimum: 0 }, endChar: { type: 'integer', minimum: 0 },
56
+ extraction: arbitraryObject, idempotencyKey: idempotency, dryRun: { type: 'boolean' },
57
+ }, ['action']),
58
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
59
+ },
60
+ {
61
+ name: 'kinedrop_hybrid_doc_and_graph',
62
+ description: 'Query tenant-scoped documents with optional content hydration, insert/get documents, add graph nodes/edges, or traverse a graph. Runtime evidence identifies the published package or development backend.',
63
+ inputSchema: object({
64
+ action: enumeration('list', 'query', 'insert', 'get', 'addNode', 'addEdge', 'walk'),
65
+ storeId: identifier, collection: identifier, documentId: identifier,
66
+ document: arbitraryObject, node: arbitraryObject, edge: arbitraryObject,
67
+ query: arbitraryObject,
68
+ startNodeId: identifier, maxDepth: { type: 'integer', minimum: 1, maximum: 3 },
69
+ idempotencyKey: idempotency, dryRun: { type: 'boolean' },
70
+ }, ['action', 'storeId']),
71
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
72
+ },
73
+ {
74
+ name: 'kinedrop_service_bus_manage_and_send',
75
+ description: 'Use the resource-selected queue backend: local SQLite or operator-bound native RabbitMQ. Send, receive, complete, abandon, or dead-letter. Full Azure Service Bus compatibility is not qualified; Kafka resources require their gateway. Receives and settlement require write access. Native operations do not support HTTP idempotency keys or dryRun.',
76
+ inputSchema: object({
77
+ action: enumeration('capabilities', 'peek', 'deadletters', 'send', 'receive', 'complete', 'abandon', 'deadletter', 'renew'),
78
+ streamId: identifier, queue: identifier, message: arbitraryObject,
79
+ messageId: identifier, lockToken: identifier,
80
+ receive: object({ maxMessages: { type: 'integer', minimum: 1, maximum: 100 }, lockSeconds: { type: 'integer', minimum: 1, maximum: 300 } }),
81
+ reason: { type: 'string', maxLength: 200 }, lockSeconds:{type:'integer',minimum:1,maximum:300}, idempotencyKey: idempotency, dryRun: { type: 'boolean' },
82
+ }, ['action', 'streamId']),
83
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
84
+ },
85
+ {
86
+ name: 'kinedrop_protect_and_migrate',
87
+ description: 'Inspect/create local catalog snapshots, or inspect/initialize/back up the resilient MongoDB profile through an explicitly configured operator binding. Human review, confirmation tokens, deletion and restore are unavailable over MCP. Native execution requires verified tools and offsite storage.',
88
+ inputSchema: object({
89
+ operation: enumeration('backups.list', 'backups.create', 'backups.get','resilience.status','resilience.plan','resilience.initialize','resilience.backup','resilience.archive'),
90
+ name: identifier, backupId: identifier, service: identifier, resourceId: identifier,
91
+ maxEntries: {type:'integer',minimum:1,maximum:10000},
92
+ idempotencyKey: idempotency, dryRun: { type: 'boolean' },
93
+ }, ['operation']),
94
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
95
+ },
96
+ {
97
+ name: 'kinedrop_mutate_or_query_data',
98
+ description: 'Call an organization-scoped data API. GET, document inspection, hybrid queries and graph walks are read-only. Other POST/PUT requests require write mode. Deletion uses a reviewed destructive plan.',
99
+ inputSchema: object({
100
+ service: enumeration('databases', 'storage', 'caches', 'streams', 'sql', 'hybrid', 'documents', 'analytics', 'search'),
101
+ method: enumeration('GET', 'POST', 'PUT'),
102
+ endpoint: { type: 'string', minLength: 1, maxLength: 1000, description: 'Slash-separated relative path below the selected service; no query, dot segments, URL, or fragment.' },
103
+ body: arbitraryObject, idempotencyKey: idempotency, dryRun: { type: 'boolean' },
104
+ }, ['service', 'method', 'endpoint']),
105
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
106
+ },
107
+ {
108
+ name:'kinedrop_object_storage_inspect',
109
+ description:'Read configured shared storage capabilities and owned account, usage, container, object, or credential metadata. No object bytes, custom metadata values, credentials, credential mutations or arbitrary routes are exposed.',
110
+ inputSchema:object({action:enumeration('capabilities','accounts.list','accounts.get','usage.get','containers.list','containers.get','objects.list','credentials.list'),accountId:identifier,container:identifier,prefix:{type:'string',maxLength:1024},delimiter:{type:'string',minLength:1,maxLength:64},cursor:{type:'string',minLength:1,maxLength:4096},limit:{type:'integer',minimum:1,maximum:5000}},['action']),
111
+ annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},
112
+ },
113
+ {
114
+ name: 'kinedrop_sandbox_exec',
115
+ description: 'Request code execution from a configured remote sandbox backend. Never runs a command or code on this station. Returns ENGINE_UNAVAILABLE when the sandbox integration is absent.',
116
+ inputSchema: object({ sandboxId: identifier, language: enumeration('python', 'javascript'), code: { type: 'string', minLength: 1, maxLength: 100_000 }, idempotencyKey: idempotency, dryRun: { type: 'boolean' } }, ['sandboxId', 'language', 'code']),
117
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
118
+ },
119
+ ...APPS_MCP_TOOLS,
120
+ ...SERVICE_MCP_TOOLS,
121
+ ...PLACEMENT_MCP_TOOLS,
122
+ ]);
123
+
124
+ export const tools = MCP_TOOLS;
125
+
126
+ function invalid(message) { return Object.assign(new Error(message), { code: 'INVALID_ARGUMENTS' }); }
127
+ function required(value, name) { if (value === undefined || value === null || value === '') throw invalid(name + ' is required for this action.'); return value; }
128
+ function id(value, name) { return encodeURIComponent(required(value, name)); }
129
+
130
+ /** Small schema validator for the exact JSON Schema subset published above. */
131
+ function validate(value, schema, path = 'arguments') {
132
+ if (schema.enum && !schema.enum.includes(value)) throw invalid(path + ' must be one of: ' + schema.enum.join(', ') + '.');
133
+ switch (schema.type) {
134
+ case 'object':
135
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalid(path + ' must be an object.');
136
+ for (const key of schema.required ?? []) if (!Object.hasOwn(value, key)) throw invalid(path + '.' + key + ' is required.');
137
+ for (const [key, item] of Object.entries(value)) {
138
+ if (['__proto__', 'prototype', 'constructor'].includes(key)) throw invalid('Unsafe object key.');
139
+ if (Object.hasOwn(schema.properties??{},key)) validate(item, schema.properties[key], path + '.' + key);
140
+ else if (schema.additionalProperties === false) throw invalid('Unknown argument ' + path + '.' + key + '.');
141
+ }
142
+ break;
143
+ case 'array':
144
+ if (!Array.isArray(value)) throw invalid(path + ' must be an array.');
145
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) throw invalid(path + ' contains too many items.');
146
+ value.forEach((item, i) => validate(item, schema.items, path + '[' + i + ']'));
147
+ break;
148
+ case 'string':
149
+ if (typeof value !== 'string') throw invalid(path + ' must be a string.');
150
+ if (schema.minLength !== undefined && value.length < schema.minLength || schema.maxLength !== undefined && value.length > schema.maxLength) throw invalid(path + ' has an invalid length.');
151
+ if (schema.pattern !== undefined && !new RegExp(schema.pattern).test(value)) throw invalid(path + ' has an invalid format.');
152
+ break;
153
+ case 'integer':
154
+ if (!Number.isInteger(value) || schema.minimum !== undefined && value < schema.minimum || schema.maximum !== undefined && value > schema.maximum) throw invalid(path + ' must be an integer within its allowed range.');
155
+ break;
156
+ case 'boolean': if (typeof value !== 'boolean') throw invalid(path + ' must be a boolean.'); break;
157
+ }
158
+ }
159
+
160
+ function assertWrite(readOnly) {
161
+ if (readOnly) throw Object.assign(new Error('This MCP server is read-only. Start with --allow-write to enable reviewed mutations.'), { code: 'READ_ONLY', status: 403 });
162
+ }
163
+
164
+ export async function dispatchTool(name, args = {}, client, { readOnly = true } = {}) {
165
+ const tool = MCP_TOOLS.find(item => item.name === name);
166
+ if (!tool) throw Object.assign(new Error('Unknown KineDrop tool.'), { code: 'UNKNOWN_TOOL' });
167
+ validate(args, tool.inputSchema);
168
+ const options = { idempotencyKey: args.idempotencyKey, dryRun: !!args.dryRun, surface:'mcp' };
169
+ if(name==='kinedrop_object_storage_inspect'){
170
+ const api=client.objectStorage,read={surface:'mcp'},action=args.action;
171
+ const allowed=['action',...(!['capabilities','accounts.list'].includes(action)?['accountId']:[]),...(['containers.get','objects.list'].includes(action)?['container']:[]),...(['containers.list','objects.list'].includes(action)?['prefix','cursor','limit']:[]),...(action==='objects.list'?['delimiter']:[])];
172
+ if(Object.keys(args).some(key=>!allowed.includes(key)))throw invalid('This selector is not supported for the storage action.');
173
+ const account=()=>required(args.accountId,'accountId'),container=()=>required(args.container,'container');
174
+ const query=Object.fromEntries(['prefix','delimiter','cursor','limit'].filter(key=>Object.hasOwn(args,key)).map(key=>[key,args[key]]));
175
+ if(action==='capabilities')return api.capabilities(read);
176
+ if(action==='accounts.list')return api.accounts.list(read);
177
+ if(action==='accounts.get')return api.accounts.get(account(),read);
178
+ if(action==='usage.get')return api.usage(account(),read);
179
+ const select=(value,fields)=>Object.fromEntries(fields.filter(key=>Object.hasOwn(value??{},key)).map(key=>[key,value[key]]));
180
+ const containerFields=['container','id','accountId','createdAt','updatedAt','generation','state'];
181
+ if(action==='containers.get')return select(await api.containers.get(account(),container(),read),containerFields);
182
+ if(action==='containers.list'){const value=await api.containers.list(account(),query,read);return {...select(value,['nextCursor']),items:(value.items??[]).map(item=>select(item,containerFields))};}
183
+ if(action==='objects.list'){const value=await api.objects.list(account(),container(),query,read),fields=['container','key','size','etag','sha256Hex','md5Hex','s3ETag','blobETag','lastModified','generation','revisionId','committed'];return {...select(value,['prefixes','nextCursor']),items:(value.items??[]).map(item=>select(item,fields))};}
184
+ if(action==='credentials.list'){
185
+ const value=await api.credentials.list(account(),read),fields=['credentialId','orgId','accountId','protocol','permissions','containers','prefix','policyRevision','createdAt','expiresAt','revoked','revokedAt'];
186
+ return {items:(value.items??[]).map(item=>Object.fromEntries(fields.filter(key=>Object.hasOwn(item,key)).map(key=>[key,item[key]])))};
187
+ }
188
+ throw invalid('This storage action is unavailable over MCP.');
189
+ }
190
+ if(name==='kinedrop_placement_inspect'){
191
+ const operation=PLACEMENT_OPERATIONS.find(op=>op.availability.mcp&&op.mcp?.action===args.action);
192
+ if(!operation||operation.http.method!=='GET'||operation.handlesSecrets||operation.humanOnly||!['placement.capabilities','onboarding.intents.list','onboarding.intents.get'].includes(operation.id))throw invalid('This placement action is not available over MCP.');
193
+ validateServiceInput(args.input,operation.input);
194
+ return client.invokePlacement(operation.id,args.input,{surface:'mcp'});
195
+ }
196
+ const serviceGroup={kinedrop_tenant_services_inspect:'inspect',kinedrop_tenant_services_manage:'manage',kinedrop_resource_protection:'protection',kinedrop_apps_maintenance_inspect:'maintenance'}[name];
197
+ if(serviceGroup){
198
+ const operation=SERVICE_OPERATIONS.find(op=>op.availability.mcp&&op.mcp?.tool===serviceGroup&&op.mcp.action===args.action);
199
+ if(!operation||operation.handlesSecrets||operation.humanOnly||operation.operatorOnly)throw invalid('This service action is not available over MCP.');
200
+ const schema={...operation.input,properties:Object.fromEntries(Object.entries(operation.input.properties).filter(([key])=>key!=='orgId')),required:operation.input.required.filter(key=>key!=='orgId')};
201
+ validateServiceInput(args.input,schema);
202
+ if(operation.risk.level!=='read')assertWrite(readOnly);
203
+ return client.invokeService(operation.id,args.input,options);
204
+ }
205
+ const appsTool=APPS_MCP_TOOLS.find(item=>item.name===name);
206
+ if(appsTool){
207
+ const operation=APPS_OPERATIONS.find(op=>op.availability.mcp&&op.mcp?.action===args.action&&('kinedrop_apps_'+op.mcp.tool)===name);
208
+ if(!operation)throw invalid('Unknown Apps action.');
209
+ if(operation.risk.level!=='read')assertWrite(readOnly);
210
+ const {action,...input}=args;
211
+ return client.apps.invoke(operation.id,input,options);
212
+ }
213
+ const request = (method, suffix, body) => {
214
+ if (!isReadOnlyRequest(method,client.orgPath(suffix))) assertWrite(readOnly);
215
+ return client.request(method, client.orgPath(suffix), body, options);
216
+ };
217
+ switch (name) {
218
+ case 'kinedrop_workspace_enrollment': {
219
+ if (args.action === 'inventory') return client.workspaces.inventory();
220
+ if (args.action === 'inspect') return client.workspaces.inspect(required(args.operationId, 'operationId'), options);
221
+ if (args.action === 'plan' || args.action === 'apply') return client.workspaces[args.action](required(args.request, 'request'), options);
222
+ throw invalid('Unsupported workspace action.');
223
+ }
224
+ case 'kinedrop_discover': {
225
+ const catalogue = await client.catalog();
226
+ return args.service ? { ...catalogue, services: (catalogue.services ?? []).filter(service => service.key === args.service || service.id === args.service) } : catalogue;
227
+ }
228
+ case 'kinedrop_inventory_and_health': {
229
+ if(client.orgId&&typeof client.diagnostics==='function'){
230
+ const diagnostics=await client.diagnostics();
231
+ const inspect=async run=>{try{return await run();}catch(error){return {items:[],error:{code:error.code??'CHECK_FAILED',message:error.message??'This area could not be inspected'}};}};
232
+ const organizations=await inspect(()=>client.orgs.list());
233
+ const resources=args.includeResources!==false?await inspect(()=>client.resources.list()):undefined;
234
+ return {health:diagnostics.checks?.health?.result??{status:'unknown'},diagnostics,organizations,...(resources?{resources}:{})};
235
+ }
236
+ const [health, organizations] = await Promise.all([client.doctor(), client.orgs.list()]);
237
+ const resources = args.includeResources !== false && client.orgId ? await client.resources.list() : undefined;
238
+ return { health, organizations, ...(resources ? { resources } : {}) };
239
+ }
240
+ case 'kinedrop_apply_blueprint':
241
+ assertWrite(readOnly);
242
+ return args.action === 'plan' ? client.stacks.plan(required(args.blueprint, 'blueprint'), options) : client.stacks.apply(required(args.planId, 'planId'), options);
243
+ case 'kinedrop_ground_and_extract_document':
244
+ if (args.action === 'list') return client.docs.bundles.list();
245
+ if (args.action === 'get') return client.docs.bundles.get(required(args.documentId, 'documentId'));
246
+ if (args.action === 'ingest') {
247
+ assertWrite(readOnly);
248
+ if ((args.text === undefined) === (args.contentBase64 === undefined)) throw invalid('Provide exactly one of text or contentBase64.');
249
+ return client.docs.ingest({ ...(args.text===undefined?{contentBase64:args.contentBase64}:{text:args.text}), fileName: args.fileName ?? 'document.md', onSecret: args.onSecret ?? 'redact' }, options);
250
+ }
251
+ if (args.action === 'resolveSpan') return client.docs.resolveSpan(required(args.documentId, 'documentId'), { startChar: required(args.startChar, 'startChar'), endChar: required(args.endChar, 'endChar') }, options);
252
+ return client.docs.extract(required(args.documentId, 'documentId'), args.extraction ?? {}, options);
253
+ case 'kinedrop_hybrid_doc_and_graph': {
254
+ const base = '/hybrid/' + id(args.storeId, 'storeId');
255
+ if (args.action === 'query') return request('POST',base+'/collections/'+id(args.collection,'collection')+'/query',args.query??{});
256
+ if (['list', 'insert', 'get'].includes(args.action)) {
257
+ const collection = base + '/collections/' + id(args.collection, 'collection') + '/documents';
258
+ if (args.action === 'list') return request('GET', collection);
259
+ if (args.action === 'get') return request('GET', collection + '/' + id(args.documentId, 'documentId'));
260
+ return request('POST', collection, required(args.document, 'document'));
261
+ }
262
+ if (args.action === 'addNode') return request('POST', base + '/graph/nodes', required(args.node, 'node'));
263
+ if (args.action === 'addEdge') return request('POST', base + '/graph/edges', required(args.edge, 'edge'));
264
+ return request('POST', base + '/graph/walk', { startNodeId: required(args.startNodeId, 'startNodeId'), maxDepth: args.maxDepth ?? 3 });
265
+ }
266
+ case 'kinedrop_service_bus_manage_and_send': {
267
+ if(args.action==='capabilities')return client.messaging.capabilities(args.streamId);
268
+ const queue = '/streams/' + id(args.streamId, 'streamId') + '/queues/' + id(args.queue, 'queue');
269
+ if(args.action==='peek'||args.action==='deadletters')return request('GET',queue+'/'+(args.action==='peek'?'messages':'deadletters'));
270
+ if (args.action === 'send') return request('POST', queue + '/messages', required(args.message, 'message'));
271
+ if (args.action === 'receive') return request('POST', queue + '/receive', args.receive ?? {});
272
+ return request('POST', queue + '/messages/' + id(args.messageId, 'messageId') + '/' + args.action, { lockToken: required(args.lockToken, 'lockToken'), ...(args.reason ? { reason: args.reason } : {}),...(args.lockSeconds===undefined?{}:{lockSeconds:args.lockSeconds}) });
273
+ }
274
+ case 'kinedrop_protect_and_migrate':
275
+ if (args.operation === 'backups.list') return client.protect.backups.list();
276
+ if (args.operation === 'backups.get') return client.protect.backups.get(required(args.backupId, 'backupId'));
277
+ if(args.operation.startsWith('resilience.')){
278
+ const instanceId=required(args.resourceId,'resourceId');
279
+ if(args.operation==='resilience.status')return client.databases.resilience.status(instanceId);
280
+ assertWrite(readOnly);
281
+ const action=args.operation.slice('resilience.'.length);
282
+ if(action==='archive')return client.databases.resilience.archive(instanceId,{...(args.maxEntries===undefined?{}:{maxEntries:args.maxEntries})},options);
283
+ return client.databases.resilience[action](instanceId,options);
284
+ }
285
+ assertWrite(readOnly);
286
+ if (args.operation === 'backups.create') return client.protect.backups.create({ name: required(args.name, 'name') }, options);
287
+ throw invalid('This action is not available over MCP.');
288
+ case 'kinedrop_mutate_or_query_data': {
289
+ const parts = args.endpoint.split('/');
290
+ if (parts.some(part => !part || part === '.' || part === '..' || /[\\?#%:\s]/.test(part))) throw invalid('endpoint must contain plain relative path segments.');
291
+ if(args.service==='databases'&&parts[1]==='resilience'&&parts[2]==='restore')throw invalid('Human restore review and confirmation are unavailable over MCP.');
292
+ if (args.method === 'GET' && args.body !== undefined) throw invalid('GET cannot contain a body.');
293
+ return request(args.method, '/' + args.service + '/' + parts.map(encodeURIComponent).join('/'), args.body);
294
+ }
295
+ case 'kinedrop_sandbox_exec':
296
+ return request('POST', '/sandboxes/' + id(args.sandboxId, 'sandboxId') + '/exec', { language: args.language, code: args.code });
297
+ }
298
+ }
299
+
300
+ const rpcError = (id, code, message, data) => ({ jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } });
301
+ export const SUPPORTED_PROTOCOL_VERSIONS=Object.freeze(['2025-03-26']);
302
+
303
+ export async function handleRpc(request, client, { readOnly = true } = {}) {
304
+ if (!request || typeof request !== 'object' || Array.isArray(request) || request.jsonrpc !== '2.0' || typeof request.method !== 'string' || (request.id !== undefined && typeof request.id !== 'string' && typeof request.id !== 'number' && request.id !== null)) {
305
+ return rpcError(null, -32600, 'Invalid JSON-RPC request.');
306
+ }
307
+ const notification = !Object.hasOwn(request, 'id');
308
+ if (notification) return null;
309
+ const id = request.id;
310
+ switch (request.method) {
311
+ case 'initialize': {
312
+ if(request.params?.protocolVersion!==undefined&&typeof request.params.protocolVersion!=='string')return rpcError(id,-32602,'protocolVersion must be a string.');
313
+ const requested=request.params?.protocolVersion;
314
+ const negotiated=SUPPORTED_PROTOCOL_VERSIONS.includes(requested)?requested:SUPPORTED_PROTOCOL_VERSIONS[0];
315
+ return { jsonrpc: '2.0', id, result: { protocolVersion: negotiated, capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'kinedrop-mcp', version: '0.1.1' }, instructions: 'Stateless JSON request/response and newline-delimited stdio profile. Native backends must be configured and verified. This connection is ' + (readOnly ? 'read-only.' : 'write-enabled; destructive actions still require single-use plans.') } };
316
+ }
317
+ case 'ping': return { jsonrpc: '2.0', id, result: {} };
318
+ case 'tools/list': return { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } };
319
+ case 'tools/call': {
320
+ if (!request.params || typeof request.params.name !== 'string') return rpcError(id, -32602, 'tools/call requires a tool name.');
321
+ if (!MCP_TOOLS.some(tool => tool.name === request.params.name)) return rpcError(id, -32602, 'Unknown KineDrop tool.');
322
+ try {
323
+ const value = await dispatchTool(request.params.name, request.params.arguments ?? {}, client, { readOnly });
324
+ if(Buffer.byteLength(JSON.stringify(value??null))>2*1024*1024)throw Object.assign(new Error('Tool result exceeds the 2 MiB limit; request a smaller page.'),{code:'RESULT_TOO_LARGE'});
325
+ return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(value ?? null) }], ...(value && typeof value === 'object' && !Array.isArray(value) ? { structuredContent: value } : {}), isError: false } };
326
+ } catch (error) {
327
+ if (error.code === 'INVALID_ARGUMENTS') return rpcError(id, -32602, error.message);
328
+ return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify({ error: { code: error?.code ?? 'TOOL_FAILED', message: error?.message ?? 'Tool failed.', ...(error?.correlationId ? { correlationId: error.correlationId } : {}) } }) }], isError: true } };
329
+ }
330
+ }
331
+ default: return rpcError(id, -32601, 'Method not found.');
332
+ }
333
+ }
334
+
335
+ export const MCP_HELP = `KineDrop MCP server (newline-delimited JSON-RPC over stdio)
336
+
337
+ node packages/kinedrop-mcp/index.mjs [--read-only | --allow-write]
338
+
339
+ Read-only is the default. Set KINEDROP_URL and KINEDROP_ORG.
340
+ Supply a short-lived Keyrox access token in KINEDROP_TOKEN, or inject
341
+ KINEDROP_KEYROX_CREDENTIAL with KINEDROP_KEYROX_ISSUER for automatic renewal.
342
+ No local shell or sandbox code is executed by this server.
343
+ `;
344
+
345
+ export async function runStdio({ argv = process.argv.slice(2), env = process.env, input = process.stdin, output = process.stdout, errorOutput = process.stderr, client: suppliedClient } = {}) {
346
+ if (argv.includes('--help') || argv.includes('-h')) { output.write(MCP_HELP); return; }
347
+ if (argv.some(arg => !['--read-only', '--allow-write'].includes(arg)) || argv.includes('--read-only') && argv.includes('--allow-write')) {
348
+ throw new Error('Use --read-only or --allow-write. Run --help for usage.');
349
+ }
350
+ const readOnly = !argv.includes('--allow-write');
351
+ const client = suppliedClient ?? new KineDropClient({ baseUrl: env.KINEDROP_URL, token: env.KINEDROP_TOKEN, keyrox: env.KINEDROP_KEYROX_CREDENTIAL === undefined ? undefined : keyroxClientOptionsFromEnv(env), orgId: env.KINEDROP_ORG, readOnly });
352
+ errorOutput.write('KineDrop MCP ready (' + (readOnly ? 'read-only' : 'write-enabled') + ').\n');
353
+ const reader = createInterface({ input, crlfDelay: Infinity, terminal: false });
354
+ for await (const line of reader) {
355
+ if (!line.trim()) continue;
356
+ if (Buffer.byteLength(line) > 3 * 1024 * 1024) { output.write(JSON.stringify(rpcError(null, -32600, 'Request exceeds the 3 MiB stdio limit.')) + '\n'); continue; }
357
+ let request;
358
+ try { request = JSON.parse(line); }
359
+ catch { output.write(JSON.stringify(rpcError(null, -32700, 'Parse error.')) + '\n'); continue; }
360
+ const response = await handleRpc(request, client, { readOnly });
361
+ if (response !== null) output.write(JSON.stringify(response) + '\n');
362
+ }
363
+ }
364
+
365
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
366
+ try { await runStdio(); }
367
+ catch (error) { process.stderr.write('KineDrop MCP: ' + (error?.message ?? 'Startup failed.') + '\n'); process.exitCode = 1; }
368
+ }
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "@x12i/kinedrop-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "license": "UNLICENSED",
5
+ "repository": { "type": "git", "url": "git+https://github.com/kinedrop/kinedrop.git", "directory": "packages/kinedrop-mcp" },
6
+ "publishConfig": { "access": "public" },
7
+ "type": "module",
8
+ "bin": { "kinedrop-mcp": "./index.mjs" },
9
+ "exports": "./index.mjs",
10
+ "engines": { "node": ">=24.0.0" },
11
+ "dependencies": { "@x12i/kinedrop": "0.1.1" },
12
+ "files": ["index.mjs"]
13
+ }
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.