@aikdna/kdna-mcp-server 0.4.1 → 0.5.0

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/README.md +204 -91
  2. package/bin/kdna-mcp.mjs +1351 -181
  3. package/package.json +18 -10
package/bin/kdna-mcp.mjs CHANGED
@@ -1,267 +1,1437 @@
1
1
  #!/usr/bin/env node
2
- import fs from 'node:fs';
3
- import os from 'node:os';
4
- import path from 'node:path';
5
- import readline from 'node:readline';
6
- import { spawnSync } from 'node:child_process';
7
- import { createRequire } from 'node:module';
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import readline from "node:readline";
6
+ import { spawnSync } from "node:child_process";
7
+ import { createHash } from "node:crypto";
8
+ import { createRequire } from "node:module";
8
9
 
9
10
  const require = createRequire(import.meta.url);
10
- const packageInfo = require('../package.json');
11
- const {
12
- detectContainerFormat,
13
- inspect,
14
- load,
15
- matchDomain,
16
- planLoad,
17
- validate,
18
- } = require('@aikdna/kdna-core');
11
+ const packageInfo = require("../package.json");
12
+ const cliPackagePath = require.resolve("@aikdna/kdna-cli/package.json");
13
+ const cliPackageInfo = require(cliPackagePath);
14
+
15
+ const ADAPTER_SCHEMA = "0.3.0";
16
+ const MAX_TASK_BYTES = 64 * 1024;
17
+ const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
18
+ const MAX_PATH_LENGTH = 4096;
19
+ const MAX_SECRET_BYTES = 16 * 1024;
20
+ const MAX_AUTHORIZATION_BYTES = MAX_SECRET_BYTES + 2;
21
+ const MAX_CONTROL_DOCUMENT_BYTES = 16 * 1024;
22
+ const AUTHORIZATION_FILE_ENV = "KDNA_MCP_AUTHORIZATION_FILE";
23
+ const WORKSPACE_ROOT_ENV = "KDNA_MCP_WORKSPACE_ROOT";
24
+ const HOST_ID_ENV = "KDNA_MCP_HOST_ID";
25
+ const HOST_PROCESSING_CONSENT_ENV = "KDNA_MCP_HOST_PROCESSING_CONSENT_FILE";
26
+ const CLI_VERSION = packageInfo.kdna_runtime?.cli;
27
+ const CORE_VERSION = packageInfo.kdna_runtime?.core;
28
+ const CLI_ENTRY = path.resolve(
29
+ path.dirname(cliPackagePath),
30
+ cliPackageInfo.bin?.kdna || "",
31
+ );
32
+ const HOME_ROOT = fs.realpathSync(os.homedir());
33
+ const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/u;
34
+ const ATTACHMENT_ID_PATTERN = /^att_[0-9a-f]{24}$/u;
35
+ const HOST_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
36
+
37
+ function bindHostWorkspaceRoot() {
38
+ const configured = process.env[WORKSPACE_ROOT_ENV];
39
+ if (
40
+ !validBoundedString(configured) ||
41
+ !path.isAbsolute(configured) ||
42
+ path.resolve(configured) !== configured
43
+ ) {
44
+ throw new Error("The KDNA MCP Host workspace root is invalid.");
45
+ }
46
+ try {
47
+ const before = fs.lstatSync(configured);
48
+ const resolved = fs.realpathSync(configured);
49
+ const opened = fs.statSync(resolved);
50
+ if (
51
+ !before.isDirectory() ||
52
+ before.isSymbolicLink() ||
53
+ !opened.isDirectory() ||
54
+ resolved !== configured ||
55
+ resolved === HOME_ROOT ||
56
+ resolved === path.parse(resolved).root
57
+ ) {
58
+ throw new Error("Host root policy");
59
+ }
60
+ return Object.freeze({
61
+ path: resolved,
62
+ dev: opened.dev,
63
+ ino: opened.ino,
64
+ });
65
+ } catch {
66
+ throw new Error("The KDNA MCP Host workspace root is invalid.");
67
+ }
68
+ }
69
+
70
+ const HOST_ROOT_BINDING = bindHostWorkspaceRoot();
71
+ const HOST_WORKSPACE_ROOT = HOST_ROOT_BINDING.path;
72
+
73
+ if (
74
+ CLI_VERSION !== "0.36.0" ||
75
+ CORE_VERSION !== "0.21.0" ||
76
+ packageInfo.kdna_runtime?.workspace_schema !== ADAPTER_SCHEMA ||
77
+ cliPackageInfo.name !== "@aikdna/kdna-cli" ||
78
+ cliPackageInfo.version !== CLI_VERSION ||
79
+ !cliPackageInfo.bin?.kdna ||
80
+ !fs.existsSync(CLI_ENTRY)
81
+ ) {
82
+ throw new Error("The KDNA MCP runtime binding is invalid.");
83
+ }
84
+
85
+ const selectionInputSchema = Object.freeze({
86
+ type: "object",
87
+ additionalProperties: false,
88
+ required: ["attachment_id", "task_digest", "approved"],
89
+ properties: Object.freeze({
90
+ attachment_id: Object.freeze({
91
+ type: "string",
92
+ pattern: "^att_[0-9a-f]{24}$",
93
+ }),
94
+ task_digest: Object.freeze({
95
+ type: "string",
96
+ pattern: "^sha256:[0-9a-f]{64}$",
97
+ }),
98
+ plan_digest: Object.freeze({
99
+ type: "string",
100
+ pattern: "^sha256:[0-9a-f]{64}$",
101
+ }),
102
+ approved: Object.freeze({ const: true }),
103
+ }),
104
+ });
19
105
 
20
106
  const tools = [
21
107
  {
22
- name: 'kdna.inspect',
23
- description: 'Inspect a .kdna asset without extracting it.',
24
- inputSchema: {
25
- type: 'object',
26
- required: ['assetPath'],
27
- properties: { assetPath: { type: 'string' }, verify: { type: 'boolean' } },
28
- },
29
- },
30
- {
31
- name: 'kdna.verify',
32
- description: 'Verify a .kdna asset integrity state.',
33
- inputSchema: {
34
- type: 'object',
35
- required: ['assetPath'],
36
- properties: {
37
- assetPath: { type: 'string' },
38
- asset_digest: { type: 'string' },
39
- content_digest: { type: 'string' },
40
- requireSignature: { type: 'boolean' },
41
- },
42
- },
43
- },
44
- {
45
- name: 'kdna.load',
46
- description: 'Load a .kdna profile and return agent context.',
108
+ name: "kdna.workspace-status",
109
+ description:
110
+ "Show only the approved attachments for the current workspace; never scan globally.",
47
111
  inputSchema: {
48
- type: 'object',
49
- required: ['assetPath'],
112
+ type: "object",
113
+ additionalProperties: false,
114
+ required: ["cwd"],
50
115
  properties: {
51
- assetPath: { type: 'string' },
52
- profile: { type: 'string', enum: ['index', 'compact', 'scenario', 'full'] },
53
- input: { type: 'string' },
54
- password: { type: 'string' },
55
- entitlementStatus: { type: 'string', enum: ['active', 'expired', 'revoked', 'offline_grace'] },
116
+ cwd: { type: "string", minLength: 1, maxLength: MAX_PATH_LENGTH },
56
117
  },
57
118
  },
58
119
  },
59
120
  {
60
- name: 'kdna.plan-load',
61
- description: 'Return the Core LoadPlan for a .kdna asset before loading.',
121
+ name: "kdna.workspace-resolve",
122
+ description:
123
+ "Resolve one task against approved attachments, including a receipt-bound one-task user selection.",
62
124
  inputSchema: {
63
- type: 'object',
64
- required: ['assetPath'],
125
+ type: "object",
126
+ additionalProperties: false,
127
+ required: ["cwd", "task"],
65
128
  properties: {
66
- assetPath: { type: 'string' },
67
- hasPassword: { type: 'boolean' },
68
- entitlementStatus: { type: 'string', enum: ['active', 'expired', 'revoked', 'offline_grace'] },
129
+ cwd: { type: "string", minLength: 1, maxLength: MAX_PATH_LENGTH },
130
+ task: { type: "string", minLength: 1, maxLength: MAX_TASK_BYTES },
131
+ selection: selectionInputSchema,
69
132
  },
70
133
  },
71
134
  },
72
135
  {
73
- name: 'kdna.available-local',
74
- description: 'List local .kdna files without using a registry.',
136
+ name: "kdna.workspace-load",
137
+ description:
138
+ "Resolve, plan, authorize, and load one approved workspace attachment, including a receipt-bound one-task user selection.",
75
139
  inputSchema: {
76
- type: 'object',
140
+ type: "object",
141
+ additionalProperties: false,
142
+ required: ["cwd", "task"],
77
143
  properties: {
78
- root: { type: 'string' },
79
- maxDepth: { type: 'number' },
80
- },
81
- },
82
- },
83
- {
84
- name: 'kdna.match',
85
- description: 'Rank .kdna assets for a task string.',
86
- inputSchema: {
87
- type: 'object',
88
- required: ['input', 'assetPaths'],
89
- properties: {
90
- input: { type: 'string' },
91
- assetPaths: { type: 'array', items: { type: 'string' } },
144
+ cwd: { type: "string", minLength: 1, maxLength: MAX_PATH_LENGTH },
145
+ task: { type: "string", minLength: 1, maxLength: MAX_TASK_BYTES },
146
+ selection: selectionInputSchema,
147
+ profile: {
148
+ type: "string",
149
+ enum: ["index", "compact", "scenario", "full"],
150
+ },
92
151
  },
93
152
  },
94
153
  },
95
154
  ];
96
155
 
97
- function send(id, result, error) {
98
- const msg = error
99
- ? { jsonrpc: '2.0', id, error: { code: -32000, message: error.message || String(error) } }
100
- : { jsonrpc: '2.0', id, result };
101
- process.stdout.write(`${JSON.stringify(msg)}\n`);
156
+ const toolDefinitions = new Map(tools.map((tool) => [tool.name, tool]));
157
+
158
+ class JsonRpcError extends Error {
159
+ constructor(code, message) {
160
+ super(message);
161
+ this.code = code;
162
+ }
163
+ }
164
+
165
+ class AdapterError extends Error {
166
+ constructor(code, message) {
167
+ super(message);
168
+ this.code = code;
169
+ }
170
+ }
171
+
172
+ function bindRotatingPrivateControlSource(environmentName) {
173
+ const configured = process.env[environmentName];
174
+ if (configured === undefined) return null;
175
+ if (
176
+ !validBoundedString(configured) ||
177
+ !path.isAbsolute(configured) ||
178
+ path.resolve(configured) !== configured
179
+ ) {
180
+ throw new Error("control coordinate policy");
181
+ }
182
+ const parent = path.dirname(configured);
183
+ const parentBefore = fs.lstatSync(parent);
184
+ if (
185
+ !parentBefore.isDirectory() ||
186
+ parentBefore.isSymbolicLink() ||
187
+ (process.platform !== "win32" &&
188
+ (parentBefore.mode & 0o077) !== 0) ||
189
+ (typeof process.getuid === "function" &&
190
+ parentBefore.uid !== process.getuid())
191
+ ) {
192
+ throw new Error("control source policy");
193
+ }
194
+ return Object.freeze({
195
+ environmentName,
196
+ path: configured,
197
+ parent,
198
+ parentDev: parentBefore.dev,
199
+ parentIno: parentBefore.ino,
200
+ });
201
+ }
202
+
203
+ function readRotatingPrivateControlDocument(source, code, message) {
204
+ if (!source) {
205
+ throw new AdapterError(code, message);
206
+ }
207
+ let descriptor;
208
+ let bytes;
209
+ try {
210
+ if (process.env[source.environmentName] !== source.path) {
211
+ throw new Error("control environment changed");
212
+ }
213
+ const parent = fs.lstatSync(source.parent);
214
+ const before = fs.lstatSync(source.path);
215
+ if (
216
+ parent.isSymbolicLink() ||
217
+ !parent.isDirectory() ||
218
+ parent.dev !== source.parentDev ||
219
+ parent.ino !== source.parentIno ||
220
+ before.isSymbolicLink() ||
221
+ !before.isFile() ||
222
+ before.size < 1 ||
223
+ before.size > MAX_CONTROL_DOCUMENT_BYTES ||
224
+ (process.platform !== "win32" && (before.mode & 0o077) !== 0) ||
225
+ (typeof process.getuid === "function" && before.uid !== process.getuid())
226
+ ) {
227
+ throw new Error("control source changed");
228
+ }
229
+ descriptor = fs.openSync(
230
+ source.path,
231
+ fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0),
232
+ );
233
+ const opened = fs.fstatSync(descriptor);
234
+ if (
235
+ !opened.isFile() ||
236
+ opened.dev !== before.dev ||
237
+ opened.ino !== before.ino ||
238
+ opened.size !== before.size ||
239
+ opened.mtimeMs !== before.mtimeMs ||
240
+ opened.ctimeMs !== before.ctimeMs
241
+ ) {
242
+ throw new Error("control source changed");
243
+ }
244
+ bytes = fs.readFileSync(descriptor);
245
+ const after = fs.fstatSync(descriptor);
246
+ const digest = `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
247
+ if (
248
+ after.dev !== opened.dev ||
249
+ after.ino !== opened.ino ||
250
+ after.size !== opened.size ||
251
+ after.mtimeMs !== opened.mtimeMs ||
252
+ after.ctimeMs !== opened.ctimeMs
253
+ ) {
254
+ throw new Error("control source changed");
255
+ }
256
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
257
+ return { document: JSON.parse(text), digest };
258
+ } catch {
259
+ throw new AdapterError(code, message);
260
+ } finally {
261
+ if (descriptor !== undefined) fs.closeSync(descriptor);
262
+ bytes?.fill(0);
263
+ }
264
+ }
265
+
266
+ let hostProcessingSource;
267
+ try {
268
+ hostProcessingSource = bindRotatingPrivateControlSource(
269
+ HOST_PROCESSING_CONSENT_ENV,
270
+ );
271
+ } catch {
272
+ hostProcessingSource = null;
273
+ }
274
+ const HOST_PROCESSING_SOURCE = hostProcessingSource;
275
+
276
+ function validatedJsonRpcMessage(message) {
277
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
278
+ throw new JsonRpcError(-32600, "Invalid Request");
279
+ }
280
+ if (message.jsonrpc !== "2.0" || typeof message.method !== "string") {
281
+ throw new JsonRpcError(-32600, "Invalid Request");
282
+ }
283
+
284
+ const hasId = Object.prototype.hasOwnProperty.call(message, "id");
285
+ if (hasId) {
286
+ const validId =
287
+ typeof message.id === "string" ||
288
+ (typeof message.id === "number" && Number.isFinite(message.id));
289
+ if (!validId) throw new JsonRpcError(-32600, "Invalid Request");
290
+ }
291
+
292
+ return {
293
+ id: message.id,
294
+ method: message.method,
295
+ params: message.params === undefined ? {} : message.params,
296
+ paramsValid:
297
+ message.params === undefined ||
298
+ (message.params !== null &&
299
+ typeof message.params === "object" &&
300
+ !Array.isArray(message.params)),
301
+ isNotification: !hasId,
302
+ };
303
+ }
304
+
305
+ function sendResult(id, result) {
306
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
307
+ }
308
+
309
+ function sendError(id, code, message) {
310
+ process.stdout.write(
311
+ `${JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })}\n`,
312
+ );
102
313
  }
103
314
 
104
315
  function textResult(value) {
105
316
  return {
106
- content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
317
+ content: [{ type: "text", text: JSON.stringify(value, null, 2) }],
318
+ };
319
+ }
320
+
321
+ function toolErrorResult(error) {
322
+ const safe =
323
+ error instanceof AdapterError
324
+ ? { code: error.code, message: error.message }
325
+ : {
326
+ code: "adapter_internal_error",
327
+ message: "The KDNA adapter could not complete the request.",
328
+ };
329
+ return {
330
+ content: [{ type: "text", text: JSON.stringify({ error: safe }, null, 2) }],
331
+ isError: true,
107
332
  };
108
333
  }
109
334
 
110
- function isKdnaAsset(assetPath) {
111
- if (!assetPath) return false;
335
+ function validBoundedString(value, maximum = MAX_PATH_LENGTH) {
336
+ return (
337
+ typeof value === "string" && value.length > 0 && value.length <= maximum
338
+ );
339
+ }
340
+
341
+ function hasExactKeys(value, required, optional = []) {
342
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
343
+ const allowed = new Set([...required, ...optional]);
344
+ return (
345
+ required.every((key) => Object.prototype.hasOwnProperty.call(value, key)) &&
346
+ Object.keys(value).every((key) => allowed.has(key))
347
+ );
348
+ }
349
+
350
+ function validateToolArguments(name, args) {
351
+ if (!toolDefinitions.has(name)) return false;
352
+ if (name === "kdna.workspace-status") {
353
+ return hasExactKeys(args, ["cwd"]) && validBoundedString(args.cwd);
354
+ }
355
+ if (["kdna.workspace-resolve", "kdna.workspace-load"].includes(name)) {
356
+ const optional =
357
+ name === "kdna.workspace-load"
358
+ ? ["profile", "selection"]
359
+ : ["selection"];
360
+ const selectionValid =
361
+ args.selection === undefined ||
362
+ (hasExactKeys(
363
+ args.selection,
364
+ ["attachment_id", "task_digest", "approved"],
365
+ ["plan_digest"],
366
+ ) &&
367
+ ATTACHMENT_ID_PATTERN.test(args.selection.attachment_id) &&
368
+ DIGEST_PATTERN.test(args.selection.task_digest) &&
369
+ (args.selection.plan_digest === undefined ||
370
+ DIGEST_PATTERN.test(args.selection.plan_digest)) &&
371
+ args.selection.approved === true);
372
+ return (
373
+ hasExactKeys(args, ["cwd", "task"], optional) &&
374
+ validBoundedString(args.cwd) &&
375
+ validBoundedString(args.task, MAX_TASK_BYTES) &&
376
+ Buffer.byteLength(args.task, "utf8") <= MAX_TASK_BYTES &&
377
+ selectionValid &&
378
+ (args.profile === undefined ||
379
+ ["index", "compact", "scenario", "full"].includes(args.profile))
380
+ );
381
+ }
382
+ return false;
383
+ }
384
+
385
+ function validatedToolCall(params) {
386
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
387
+ throw new JsonRpcError(-32602, "Invalid params");
388
+ }
389
+ if (typeof params.name !== "string" || !toolDefinitions.has(params.name)) {
390
+ throw new JsonRpcError(-32602, "Invalid params");
391
+ }
392
+ const args = params.arguments === undefined ? {} : params.arguments;
393
+ if (!validateToolArguments(params.name, args))
394
+ throw new JsonRpcError(-32602, "Invalid params");
395
+ return { name: params.name, args };
396
+ }
397
+
398
+ function parseCliJson(result, acceptedStatuses) {
399
+ if (result.error) {
400
+ throw new AdapterError(
401
+ "runtime_unavailable",
402
+ "The pinned KDNA CLI runtime is unavailable.",
403
+ );
404
+ }
405
+ if (!acceptedStatuses.has(result.status)) {
406
+ throw new AdapterError(
407
+ "runtime_rejected",
408
+ "The pinned KDNA CLI rejected the request.",
409
+ );
410
+ }
411
+ if (
412
+ !result.stdout ||
413
+ Buffer.byteLength(result.stdout, "utf8") > MAX_OUTPUT_BYTES
414
+ ) {
415
+ throw new AdapterError(
416
+ "runtime_output_invalid",
417
+ "The pinned KDNA CLI returned invalid output.",
418
+ );
419
+ }
112
420
  try {
113
- if (!fs.existsSync(assetPath) || !fs.statSync(assetPath).isFile()) return false;
114
- return assetPath.endsWith('.kdna') && detectContainerFormat(assetPath) === 'kdna';
421
+ return JSON.parse(result.stdout);
115
422
  } catch {
116
- return false;
423
+ throw new AdapterError(
424
+ "runtime_output_invalid",
425
+ "The pinned KDNA CLI returned invalid output.",
426
+ );
117
427
  }
118
428
  }
119
429
 
120
- function defaultAssetRoot() {
121
- return process.env.KDNA_ASSET_DIR || process.env.KDNA_PACKAGE_DIR || path.join(os.homedir(), '.kdna', 'packages');
430
+ function cliEnvironment() {
431
+ const environment = { ...process.env };
432
+ delete environment[AUTHORIZATION_FILE_ENV];
433
+ delete environment[WORKSPACE_ROOT_ENV];
434
+ delete environment[HOST_ID_ENV];
435
+ delete environment[HOST_PROCESSING_CONSENT_ENV];
436
+ return environment;
437
+ }
438
+
439
+ function runCliJson(args, options = {}) {
440
+ const result = spawnSync(process.execPath, [CLI_ENTRY, ...args], {
441
+ cwd: options.cwd || HOST_WORKSPACE_ROOT,
442
+ env: cliEnvironment(),
443
+ input: options.input,
444
+ encoding: "utf8",
445
+ timeout: 30_000,
446
+ maxBuffer: MAX_OUTPUT_BYTES,
447
+ shell: false,
448
+ stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
449
+ });
450
+ return parseCliJson(result, new Set(options.acceptedStatuses || [0]));
451
+ }
452
+
453
+ function authorizationSourceConfigured() {
454
+ return validBoundedString(process.env[AUTHORIZATION_FILE_ENV]);
122
455
  }
123
456
 
124
- function findLocalAssets(root = defaultAssetRoot(), maxDepth = 3) {
125
- if (!root || !fs.existsSync(root)) return [];
126
- const found = [];
457
+ function bindAuthorizationSource() {
458
+ const configured = process.env[AUTHORIZATION_FILE_ENV];
459
+ if (!validBoundedString(configured) || !path.isAbsolute(configured)) {
460
+ throw new AdapterError(
461
+ "authorization_source_invalid",
462
+ "The process authorization source is invalid.",
463
+ );
464
+ }
127
465
 
128
- function visit(dir, depth) {
129
- if (depth > maxDepth) return;
130
- let entries;
131
- try {
132
- entries = fs.readdirSync(dir, { withFileTypes: true });
133
- } catch {
134
- return;
466
+ try {
467
+ const before = fs.lstatSync(configured);
468
+ if (
469
+ !before.isFile() ||
470
+ before.isSymbolicLink() ||
471
+ before.size < 1 ||
472
+ before.size > MAX_AUTHORIZATION_BYTES ||
473
+ (process.platform !== "win32" && (before.mode & 0o077) !== 0) ||
474
+ (typeof process.getuid === "function" && before.uid !== process.getuid())
475
+ ) {
476
+ throw new Error("authorization source policy");
477
+ }
478
+ return {
479
+ path: configured,
480
+ dev: before.dev,
481
+ ino: before.ino,
482
+ size: before.size,
483
+ mtimeMs: before.mtimeMs,
484
+ ctimeMs: before.ctimeMs,
485
+ };
486
+ } catch {
487
+ throw new AdapterError(
488
+ "authorization_source_invalid",
489
+ "The process authorization source is invalid.",
490
+ );
491
+ }
492
+ }
493
+
494
+ function authorizationFactsMatch(stat, binding) {
495
+ return (
496
+ stat.dev === binding.dev &&
497
+ stat.ino === binding.ino &&
498
+ stat.size === binding.size &&
499
+ stat.mtimeMs === binding.mtimeMs &&
500
+ stat.ctimeMs === binding.ctimeMs
501
+ );
502
+ }
503
+
504
+ function readAuthorizationInput(binding) {
505
+ const configured = process.env[AUTHORIZATION_FILE_ENV];
506
+ if (!binding || configured !== binding.path) {
507
+ throw new AdapterError(
508
+ "authorization_source_invalid",
509
+ "The process authorization source is invalid.",
510
+ );
511
+ }
512
+
513
+ let descriptor;
514
+ let bytes;
515
+ try {
516
+ const before = fs.lstatSync(configured);
517
+ if (
518
+ before.isSymbolicLink() ||
519
+ !before.isFile() ||
520
+ !authorizationFactsMatch(before, binding)
521
+ ) {
522
+ throw new Error("authorization source changed");
523
+ }
524
+ descriptor = fs.openSync(
525
+ configured,
526
+ fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0),
527
+ );
528
+ const opened = fs.fstatSync(descriptor);
529
+ if (!opened.isFile() || !authorizationFactsMatch(opened, binding)) {
530
+ throw new Error("authorization source changed");
531
+ }
532
+ bytes = fs.readFileSync(descriptor);
533
+ const after = fs.fstatSync(descriptor);
534
+ if (
535
+ !authorizationFactsMatch(after, binding) ||
536
+ !authorizationFactsMatch(opened, binding)
537
+ ) {
538
+ throw new Error("authorization source changed");
539
+ }
540
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes);
541
+ let end = bytes.length;
542
+ if (end >= 2 && bytes[end - 2] === 0x0d && bytes[end - 1] === 0x0a) {
543
+ end -= 2;
544
+ } else if (end >= 1 && bytes[end - 1] === 0x0a) {
545
+ end -= 1;
135
546
  }
547
+ if (end < 1 || end > MAX_SECRET_BYTES) {
548
+ throw new Error("authorization source is empty");
549
+ }
550
+ return Buffer.from(bytes.subarray(0, end));
551
+ } catch {
552
+ throw new AdapterError(
553
+ "authorization_source_invalid",
554
+ "The process authorization source is invalid.",
555
+ );
556
+ } finally {
557
+ if (descriptor !== undefined) fs.closeSync(descriptor);
558
+ bytes?.fill(0);
559
+ }
560
+ }
136
561
 
137
- for (const entry of entries) {
138
- if (entry.name === 'node_modules' || entry.name === '.git') continue;
139
- const full = path.join(dir, entry.name);
140
- if (entry.isDirectory()) {
141
- visit(full, depth + 1);
142
- } else if (entry.isFile() && entry.name.endsWith('.kdna') && detectContainerFormat(full) === 'kdna') {
143
- const inspection = inspect(full);
144
- const validation = validate(full);
145
- found.push({
146
- path: full,
147
- kind: 'kdna_asset',
148
- asset_id: inspection.asset_id,
149
- title: inspection.title,
150
- version: inspection.version,
151
- judgment_version: inspection.judgment_version,
152
- checksums_present: Boolean(inspection.checksums_present),
153
- loadable: Boolean(validation.overall_valid),
154
- problems: validation.overall_valid ? [] : validation.problems || [],
155
- });
156
- }
562
+ function passwordRequiredByPlan(loadPlan) {
563
+ return (
564
+ loadPlan?.state === "needs_password" &&
565
+ loadPlan?.issues?.some(
566
+ (issue) => issue?.code === "KDNA_AUTH_PASSWORD_REQUIRED",
567
+ )
568
+ );
569
+ }
570
+
571
+ function loadRuntimeCapsule(
572
+ assetPath,
573
+ profile,
574
+ loadPlan,
575
+ authorizationBinding = null,
576
+ ) {
577
+ let authorizationInput;
578
+ if (loadPlan?.can_load_now !== true && passwordRequiredByPlan(loadPlan)) {
579
+ if (!authorizationSourceConfigured()) {
580
+ throw new AdapterError(
581
+ "authorization_required",
582
+ "The selected asset is not authorized for loading.",
583
+ );
157
584
  }
585
+ authorizationInput = readAuthorizationInput(authorizationBinding);
586
+ } else if (loadPlan?.can_load_now !== true) {
587
+ throw new AdapterError(
588
+ "authorization_required",
589
+ "The selected asset is not authorized for loading.",
590
+ );
158
591
  }
159
592
 
160
- visit(path.resolve(root), 0);
161
- return found;
593
+ try {
594
+ const loadArguments = [
595
+ "load",
596
+ assetPath,
597
+ `--profile=${profile || "compact"}`,
598
+ "--as=json",
599
+ ];
600
+ if (authorizationInput) loadArguments.push("--password-stdin");
601
+ return runCliJson(loadArguments, { input: authorizationInput });
602
+ } catch (error) {
603
+ if (
604
+ authorizationInput &&
605
+ error instanceof AdapterError &&
606
+ error.code === "runtime_rejected"
607
+ ) {
608
+ throw new AdapterError(
609
+ "authorization_rejected",
610
+ "The process authorization source did not authorize the load.",
611
+ );
612
+ }
613
+ throw error;
614
+ } finally {
615
+ authorizationInput?.fill(0);
616
+ }
162
617
  }
163
618
 
164
- function runCliPlanLoad(args = {}) {
165
- const cliArgs = ['plan-load', args.assetPath, '--json'];
166
- if (args.hasPassword) cliArgs.push('--has-password');
167
- if (args.entitlementStatus) cliArgs.push('--entitlement-status', args.entitlementStatus);
619
+ function digestText(value) {
620
+ return `sha256:${createHash("sha256").update(value, "utf8").digest("hex")}`;
621
+ }
168
622
 
169
- const result = spawnSync('kdna', cliArgs, {
170
- encoding: 'utf8',
171
- timeout: 30_000,
623
+ function hostProcessingConsent(assetDigest, profile, expectedUseBoundary) {
624
+ if (!HOST_PROCESSING_SOURCE) {
625
+ throw new AdapterError(
626
+ "host_processing_consent_required",
627
+ "Host processing consent is required before any Runtime Capsule delivery.",
628
+ );
629
+ }
630
+ const { document, digest } = readRotatingPrivateControlDocument(
631
+ HOST_PROCESSING_SOURCE,
632
+ "host_processing_consent_invalid",
633
+ "The Host processing consent is invalid or unavailable.",
634
+ );
635
+ const hostId = process.env[HOST_ID_ENV];
636
+ const boundary = document?.processing_boundary;
637
+ if (
638
+ !HOST_ID_PATTERN.test(hostId || "") ||
639
+ !hasExactKeys(document, [
640
+ "document_type",
641
+ "schema_version",
642
+ "nonce",
643
+ "host_id",
644
+ "workspace_root_digest",
645
+ "asset_digest",
646
+ "use_boundary",
647
+ "processing_boundary",
648
+ "capsule_profile",
649
+ "approval_source",
650
+ "approved",
651
+ ]) ||
652
+ document.document_type !== "kdna.mcp.host-processing-consent" ||
653
+ document.schema_version !== "0.1.0" ||
654
+ !/^[0-9a-f]{32}$/u.test(document.nonce) ||
655
+ document.host_id !== hostId ||
656
+ document.workspace_root_digest !== digestText(HOST_WORKSPACE_ROOT) ||
657
+ document.asset_digest !== assetDigest ||
658
+ JSON.stringify(document.use_boundary) !==
659
+ JSON.stringify(expectedUseBoundary) ||
660
+ document.capsule_profile !== (profile || "compact") ||
661
+ document.approval_source !== "user_explicit_natural_language" ||
662
+ document.approved !== true ||
663
+ !boundary ||
664
+ typeof boundary !== "object" ||
665
+ Array.isArray(boundary)
666
+ ) {
667
+ throw new AdapterError(
668
+ "host_processing_consent_invalid",
669
+ "The Host processing consent is invalid.",
670
+ );
671
+ }
672
+ if (boundary.kind === "verified_local_only") {
673
+ throw new AdapterError(
674
+ "local_processing_attestation_required",
675
+ "This adapter cannot accept a Host's unverified local-only claim.",
676
+ );
677
+ }
678
+ if (
679
+ !hasExactKeys(boundary, ["kind", "processor"]) ||
680
+ boundary.kind !== "named_remote" ||
681
+ !validBoundedString(boundary.processor, 256)
682
+ ) {
683
+ throw new AdapterError(
684
+ "host_processing_destination_unknown",
685
+ "The Host processing destination is unknown.",
686
+ );
687
+ }
688
+ return Object.freeze({
689
+ document_type: "kdna.mcp.host-processing-binding",
690
+ schema_version: "0.1.0",
691
+ host_id: document.host_id,
692
+ processing_boundary: Object.freeze({
693
+ kind: boundary.kind,
694
+ processor: boundary.processor,
695
+ }),
696
+ capsule_profile: document.capsule_profile,
697
+ asset_digest: document.asset_digest,
698
+ use_boundary: Object.freeze({ ...document.use_boundary }),
699
+ workspace_root_digest: document.workspace_root_digest,
700
+ approval_source: document.approval_source,
701
+ consent_digest: digest,
172
702
  });
703
+ }
173
704
 
174
- if (result.error) {
175
- throw new Error(`Core planLoad is unavailable and kdna CLI failed: ${result.error.message}`);
705
+ function assertHostRootBinding() {
706
+ try {
707
+ const current = fs.lstatSync(HOST_WORKSPACE_ROOT);
708
+ const resolved = fs.realpathSync(HOST_WORKSPACE_ROOT);
709
+ const opened = fs.statSync(resolved);
710
+ if (
711
+ current.isSymbolicLink() ||
712
+ !current.isDirectory() ||
713
+ !opened.isDirectory() ||
714
+ resolved !== HOST_WORKSPACE_ROOT ||
715
+ opened.dev !== HOST_ROOT_BINDING.dev ||
716
+ opened.ino !== HOST_ROOT_BINDING.ino
717
+ ) {
718
+ throw new Error("Host root changed");
719
+ }
720
+ } catch {
721
+ throw new AdapterError(
722
+ "host_workspace_root_changed",
723
+ "The Host workspace root changed after MCP startup.",
724
+ );
176
725
  }
726
+ }
727
+
728
+ function withinHostRoot(candidate) {
729
+ assertHostRootBinding();
730
+ const relative = path.relative(HOST_WORKSPACE_ROOT, candidate);
731
+ return (
732
+ relative === "" ||
733
+ (!relative.startsWith(`..${path.sep}`) &&
734
+ relative !== ".." &&
735
+ !path.isAbsolute(relative))
736
+ );
737
+ }
738
+
739
+ function workspaceCwd(value) {
740
+ let resolved;
177
741
  try {
178
- if (result.stdout && result.stdout.trim()) return JSON.parse(result.stdout);
179
- } catch (error) {
180
- throw new Error(`Core planLoad is unavailable and kdna CLI returned non-JSON output: ${error.message}`);
742
+ const requested = path.resolve(value);
743
+ const requestedStat = fs.lstatSync(requested);
744
+ if (requestedStat.isSymbolicLink() || !requestedStat.isDirectory()) {
745
+ throw new Error("not a regular directory");
746
+ }
747
+ resolved = fs.realpathSync(requested);
748
+ } catch {
749
+ throw new AdapterError(
750
+ "workspace_unavailable",
751
+ "The requested Host workspace is unavailable.",
752
+ );
181
753
  }
182
- if (result.status !== 0) {
183
- throw new Error(`Core planLoad is unavailable and kdna CLI exited ${result.status}: ${result.stderr || result.stdout}`);
754
+ if (!withinHostRoot(resolved)) {
755
+ throw new AdapterError(
756
+ "workspace_outside_host_root",
757
+ "The requested workspace is outside the current Host root.",
758
+ );
184
759
  }
185
- throw new Error('Core planLoad is unavailable and kdna CLI returned empty output');
760
+ return resolved;
186
761
  }
187
762
 
188
- function planLoadThroughCoreOrCli(args = {}) {
189
- if (!args.assetPath) throw new Error('assetPath is required');
763
+ function bindingChanged() {
764
+ throw new AdapterError(
765
+ "workspace_binding_changed",
766
+ "The approved workspace attachment changed during loading.",
767
+ );
768
+ }
190
769
 
191
- if (typeof planLoad === 'function' && process.env.KDNA_MCP_FORCE_CLI_PLAN_LOAD !== '1') {
192
- return planLoad(args.assetPath, {
193
- hasPassword: Boolean(args.hasPassword),
194
- entitlement: args.entitlementStatus ? { status: args.entitlementStatus } : undefined,
195
- });
770
+ function readRecordBytes(recordPath, changed = false) {
771
+ let descriptor;
772
+ try {
773
+ descriptor = fs.openSync(
774
+ recordPath,
775
+ fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0),
776
+ );
777
+ const stat = fs.fstatSync(descriptor);
778
+ if (!stat.isFile() || stat.size > MAX_OUTPUT_BYTES) {
779
+ throw new Error("invalid attachment record");
780
+ }
781
+ return fs.readFileSync(descriptor);
782
+ } catch {
783
+ if (changed) bindingChanged();
784
+ throw new AdapterError(
785
+ "workspace_contract_invalid",
786
+ "The workspace attachment record is invalid.",
787
+ );
788
+ } finally {
789
+ if (descriptor !== undefined) fs.closeSync(descriptor);
790
+ }
791
+ }
792
+
793
+ function recordDigest(bytes) {
794
+ return createHash("sha256").update(bytes).digest("hex");
795
+ }
796
+
797
+ function findWorkspaceBinding(cwd) {
798
+ const safeCwd = workspaceCwd(cwd);
799
+ let current = safeCwd;
800
+ while (true) {
801
+ const recordPath = path.join(current, ".kdna", "attachments.json");
802
+ let recordExists = false;
803
+ try {
804
+ const kdnaStat = fs.lstatSync(path.dirname(recordPath));
805
+ if (kdnaStat.isSymbolicLink() || !kdnaStat.isDirectory()) {
806
+ throw new AdapterError(
807
+ "workspace_contract_invalid",
808
+ "The workspace attachment directory is invalid.",
809
+ );
810
+ }
811
+ const stat = fs.lstatSync(recordPath);
812
+ if (stat.isSymbolicLink() || !stat.isFile()) {
813
+ throw new AdapterError(
814
+ "workspace_contract_invalid",
815
+ "The workspace attachment record is invalid.",
816
+ );
817
+ }
818
+ recordExists = true;
819
+ } catch (error) {
820
+ if (error instanceof AdapterError) throw error;
821
+ if (error?.code !== "ENOENT") {
822
+ throw new AdapterError(
823
+ "workspace_contract_invalid",
824
+ "The workspace attachment record is invalid.",
825
+ );
826
+ }
827
+ }
828
+ if (recordExists) {
829
+ if (current === HOME_ROOT) {
830
+ throw new AdapterError(
831
+ "workspace_home_ambiguous",
832
+ "The home-level .kdna directory cannot act as project attachment authority.",
833
+ );
834
+ }
835
+ const bytes = readRecordBytes(recordPath);
836
+ return {
837
+ safeCwd,
838
+ workspaceRoot: current,
839
+ recordPath,
840
+ recordDigest: recordDigest(bytes),
841
+ };
842
+ }
843
+ if (current === HOST_WORKSPACE_ROOT) return null;
844
+ const parent = path.dirname(current);
845
+ if (parent === current || !withinHostRoot(parent)) return null;
846
+ current = parent;
196
847
  }
848
+ }
849
+
850
+ function assertRecordBinding(binding) {
851
+ const bytes = readRecordBytes(binding.recordPath, true);
852
+ if (recordDigest(bytes) !== binding.recordDigest) bindingChanged();
853
+ }
854
+
855
+ function noAttachmentResolution() {
856
+ return {
857
+ document_type: "kdna.workspace-resolution",
858
+ schema_version: ADAPTER_SCHEMA,
859
+ decision: "skip",
860
+ reason_code: "no_approved_attachment",
861
+ workspace_root: ".",
862
+ selected: null,
863
+ candidates: [],
864
+ authorization: "not_checked",
865
+ integrity: "not_checked",
866
+ };
867
+ }
868
+
869
+ function validCandidate(candidate) {
870
+ return (
871
+ hasExactKeys(candidate, [
872
+ "attachment_id",
873
+ "asset_id",
874
+ "version",
875
+ "digest",
876
+ "role",
877
+ "authorization",
878
+ "integrity",
879
+ ]) &&
880
+ ATTACHMENT_ID_PATTERN.test(candidate.attachment_id) &&
881
+ validBoundedString(candidate.asset_id, 512) &&
882
+ validBoundedString(candidate.version, 128) &&
883
+ DIGEST_PATTERN.test(candidate.digest) &&
884
+ validBoundedString(candidate.role, 512) &&
885
+ ["not_checked", "required", "satisfied"].includes(
886
+ candidate.authorization,
887
+ ) &&
888
+ ["not_checked", "verified", "failed"].includes(candidate.integrity)
889
+ );
890
+ }
891
+
892
+ function validSelectionPlan(plan) {
893
+ return (
894
+ hasExactKeys(plan, [
895
+ "document_type",
896
+ "schema_version",
897
+ "workspace_root",
898
+ "task_digest",
899
+ "record_digest",
900
+ "candidate_set_digest",
901
+ "plan_digest",
902
+ ]) &&
903
+ plan.document_type === "kdna.workspace-selection-plan" &&
904
+ plan.schema_version === ADAPTER_SCHEMA &&
905
+ validBoundedString(plan.workspace_root) &&
906
+ !path.isAbsolute(plan.workspace_root) &&
907
+ DIGEST_PATTERN.test(plan.task_digest) &&
908
+ DIGEST_PATTERN.test(plan.record_digest) &&
909
+ DIGEST_PATTERN.test(plan.candidate_set_digest) &&
910
+ DIGEST_PATTERN.test(plan.plan_digest)
911
+ );
912
+ }
913
+
914
+ function validateResolution(resolution, options = {}) {
915
+ const reasons = new Set([
916
+ "single_approved_attachment_clearly_applies",
917
+ "explicit_task_attachment_selection",
918
+ "no_approved_attachment",
919
+ "explicitly_outside_scope",
920
+ "closed_world_no_match",
921
+ "no_applicable_attachment",
922
+ "applicability_unresolved",
923
+ "ambiguous_scope",
924
+ "attachment_conflict",
925
+ "adapter_incompatible",
926
+ "attachment_schema_unsupported",
927
+ "snapshot_missing",
928
+ "snapshot_digest_mismatch",
929
+ "asset_invalid",
930
+ "authorization_required",
931
+ "selection_binding_changed",
932
+ "selection_not_current_candidate",
933
+ "selection_receipt_required",
934
+ ]);
935
+ const exact = hasExactKeys(
936
+ resolution,
937
+ [
938
+ "document_type",
939
+ "schema_version",
940
+ "decision",
941
+ "reason_code",
942
+ "workspace_root",
943
+ "selected",
944
+ "candidates",
945
+ "authorization",
946
+ "integrity",
947
+ ],
948
+ ["selection_plan"],
949
+ );
950
+ const valid =
951
+ exact &&
952
+ resolution.document_type === "kdna.workspace-resolution" &&
953
+ resolution.schema_version === ADAPTER_SCHEMA &&
954
+ ["load", "ask", "skip", "block"].includes(resolution.decision) &&
955
+ reasons.has(resolution.reason_code) &&
956
+ validBoundedString(resolution.workspace_root) &&
957
+ !path.isAbsolute(resolution.workspace_root) &&
958
+ !resolution.workspace_root.includes("\0") &&
959
+ Array.isArray(resolution.candidates) &&
960
+ resolution.candidates.length <= 64 &&
961
+ resolution.candidates.every(validCandidate) &&
962
+ ["not_checked", "not_selected", "required", "satisfied"].includes(
963
+ resolution.authorization,
964
+ ) &&
965
+ ["not_checked", "verified", "failed"].includes(resolution.integrity) &&
966
+ (resolution.selected === null || validCandidate(resolution.selected));
197
967
 
198
- return runCliPlanLoad(args);
968
+ if (
969
+ !valid ||
970
+ (resolution.decision === "load") !== (resolution.selected !== null) ||
971
+ (resolution.decision === "ask") !==
972
+ Object.prototype.hasOwnProperty.call(resolution, "selection_plan") ||
973
+ (resolution.decision === "ask" &&
974
+ !validSelectionPlan(resolution.selection_plan))
975
+ ) {
976
+ throw new AdapterError(
977
+ "resolver_contract_invalid",
978
+ "The official resolver returned an invalid contract.",
979
+ );
980
+ }
981
+ if (
982
+ resolution.decision === "load" &&
983
+ (!(
984
+ resolution.authorization === "satisfied" ||
985
+ (options.allowDeferredPasswordAuthorization === true &&
986
+ resolution.authorization === "required")
987
+ ) ||
988
+ resolution.integrity !== "verified")
989
+ ) {
990
+ throw new AdapterError(
991
+ "resolver_contract_invalid",
992
+ "The official resolver returned an invalid contract.",
993
+ );
994
+ }
995
+ return resolution;
199
996
  }
200
997
 
201
- async function callTool(name, args = {}) {
202
- if (name === 'kdna.inspect') {
203
- if (!isKdnaAsset(args.assetPath)) throw new Error('assetPath is not a current KDNA asset');
204
- return textResult(inspect(args.assetPath, { verify: args.verify !== false }));
998
+ function resolvedWorkspaceRoot(binding, resolution) {
999
+ const candidate = path.resolve(binding.safeCwd, resolution.workspace_root);
1000
+ if (!withinHostRoot(candidate)) bindingChanged();
1001
+ let resolved;
1002
+ try {
1003
+ resolved = fs.realpathSync(candidate);
1004
+ if (!fs.statSync(resolved).isDirectory()) bindingChanged();
1005
+ } catch {
1006
+ bindingChanged();
205
1007
  }
206
- if (name === 'kdna.verify') {
207
- if (!isKdnaAsset(args.assetPath)) throw new Error('assetPath is not a current KDNA asset');
208
- return textResult(validate(args.assetPath, {
209
- asset_digest: args.asset_digest,
210
- content_digest: args.content_digest,
211
- requireSignature: Boolean(args.requireSignature),
212
- }));
1008
+ if (resolved !== binding.workspaceRoot) bindingChanged();
1009
+ return resolved;
1010
+ }
1011
+
1012
+ function validateWorkspaceRecord(record) {
1013
+ if (
1014
+ !hasExactKeys(record, [
1015
+ "document_type",
1016
+ "schema_version",
1017
+ "workspace",
1018
+ "attachments",
1019
+ ]) ||
1020
+ record.document_type !== "kdna.workspace-attachments" ||
1021
+ record.schema_version !== ADAPTER_SCHEMA ||
1022
+ !Array.isArray(record.attachments)
1023
+ ) {
1024
+ throw new AdapterError(
1025
+ "workspace_contract_invalid",
1026
+ "The workspace attachment record is invalid.",
1027
+ );
213
1028
  }
214
- if (name === 'kdna.load') {
215
- if (!isKdnaAsset(args.assetPath)) throw new Error('assetPath is not a current KDNA asset');
216
- return textResult(load(args.assetPath, {
217
- profile: args.profile || 'compact',
218
- as: 'json',
219
- input: args.input || '',
220
- password: args.password,
221
- entitlement: args.entitlementStatus ? { status: args.entitlementStatus } : undefined,
222
- }));
1029
+ return record;
1030
+ }
1031
+
1032
+ function recordAtBinding(binding) {
1033
+ assertRecordBinding(binding);
1034
+ const record = validateWorkspaceRecord(
1035
+ runCliJson([
1036
+ "attachments",
1037
+ "--cwd",
1038
+ binding.workspaceRoot,
1039
+ "--workspace-root",
1040
+ HOST_WORKSPACE_ROOT,
1041
+ ]),
1042
+ );
1043
+ assertRecordBinding(binding);
1044
+ return record;
1045
+ }
1046
+
1047
+ function bindSelectedAttachment(binding, selected) {
1048
+ const record = recordAtBinding(binding);
1049
+ const attachment = record.attachments.find(
1050
+ (item) => item?.attachment_id === selected.attachment_id,
1051
+ );
1052
+ if (
1053
+ !attachment ||
1054
+ attachment.state !== "enabled" ||
1055
+ attachment.role !== selected.role ||
1056
+ attachment.asset?.id !== selected.asset_id ||
1057
+ attachment.asset?.version !== selected.version ||
1058
+ attachment.asset?.digest !== selected.digest ||
1059
+ attachment.scope?.kind !== "workspace" ||
1060
+ !["task_hints", "all_workspace"].includes(attachment.scope.application) ||
1061
+ attachment.scope.authority !== "user_approved_routing_hint" ||
1062
+ !["open_world_ask", "closed_world_skip", "all_workspace"].includes(
1063
+ attachment.scope.matching_policy,
1064
+ ) ||
1065
+ !["user_explicit", "preview_confirmed"].includes(
1066
+ attachment.scope.approval_source,
1067
+ ) ||
1068
+ !Array.isArray(attachment.scope.applies_to) ||
1069
+ !Array.isArray(attachment.scope.does_not_apply_to) ||
1070
+ !validBoundedString(attachment.asset?.snapshot)
1071
+ ) {
1072
+ bindingChanged();
223
1073
  }
224
- if (name === 'kdna.plan-load') {
225
- return textResult(planLoadThroughCoreOrCli(args));
1074
+
1075
+ const protectedRoot = path.join(binding.workspaceRoot, ".kdna", "assets");
1076
+ const snapshot = path.resolve(
1077
+ binding.workspaceRoot,
1078
+ ".kdna",
1079
+ attachment.asset.snapshot,
1080
+ );
1081
+ const relative = path.relative(protectedRoot, snapshot);
1082
+ if (
1083
+ relative === "" ||
1084
+ relative.startsWith(`..${path.sep}`) ||
1085
+ relative === ".." ||
1086
+ path.isAbsolute(relative)
1087
+ ) {
1088
+ bindingChanged();
226
1089
  }
227
- if (name === 'kdna.match') {
228
- return textResult(await matchDomain(args.input || '', args.assetPaths || []));
1090
+
1091
+ return {
1092
+ ...binding,
1093
+ selected,
1094
+ scope: attachment.scope,
1095
+ snapshot,
1096
+ };
1097
+ }
1098
+
1099
+ function snapshotDigest(snapshot) {
1100
+ let descriptor;
1101
+ try {
1102
+ descriptor = fs.openSync(
1103
+ snapshot,
1104
+ fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0),
1105
+ );
1106
+ if (!fs.fstatSync(descriptor).isFile()) bindingChanged();
1107
+ const hash = createHash("sha256");
1108
+ const buffer = Buffer.allocUnsafe(64 * 1024);
1109
+ let bytesRead;
1110
+ do {
1111
+ bytesRead = fs.readSync(descriptor, buffer, 0, buffer.length, null);
1112
+ if (bytesRead > 0) hash.update(buffer.subarray(0, bytesRead));
1113
+ } while (bytesRead > 0);
1114
+ return `sha256:${hash.digest("hex")}`;
1115
+ } catch {
1116
+ bindingChanged();
1117
+ } finally {
1118
+ if (descriptor !== undefined) fs.closeSync(descriptor);
229
1119
  }
230
- if (name === 'kdna.available-local') {
231
- return textResult(findLocalAssets(args.root, args.maxDepth || 3));
1120
+ }
1121
+
1122
+ function assertWorkspaceBinding(binding) {
1123
+ assertRecordBinding(binding);
1124
+ const record = recordAtBinding(binding);
1125
+ const attachment = record.attachments.find(
1126
+ (item) => item?.attachment_id === binding.selected.attachment_id,
1127
+ );
1128
+ if (
1129
+ !attachment ||
1130
+ attachment.state !== "enabled" ||
1131
+ attachment.role !== binding.selected.role ||
1132
+ attachment.asset?.id !== binding.selected.asset_id ||
1133
+ attachment.asset?.version !== binding.selected.version ||
1134
+ attachment.asset?.digest !== binding.selected.digest ||
1135
+ attachment.asset?.snapshot === undefined ||
1136
+ path.resolve(binding.workspaceRoot, ".kdna", attachment.asset.snapshot) !==
1137
+ binding.snapshot ||
1138
+ JSON.stringify(attachment.scope) !== JSON.stringify(binding.scope) ||
1139
+ snapshotDigest(binding.snapshot) !== binding.selected.digest
1140
+ ) {
1141
+ bindingChanged();
232
1142
  }
233
- throw new Error(`Unknown tool: ${name}`);
234
1143
  }
235
1144
 
236
- async function handle(message) {
237
- const { id, method, params = {} } = message;
238
- if (method === 'initialize') {
239
- send(id, {
240
- protocolVersion: '2024-11-05',
1145
+ function resolveWorkspaceContext(cwd, task, selection = undefined) {
1146
+ const binding = findWorkspaceBinding(cwd);
1147
+ if (binding === null) {
1148
+ return { resolution: noAttachmentResolution(), binding: null };
1149
+ }
1150
+ const taskInput = Buffer.from(task, "utf8");
1151
+ if (taskInput.toString("utf8") !== task) {
1152
+ taskInput.fill(0);
1153
+ throw new AdapterError(
1154
+ "task_input_invalid",
1155
+ "The task input is not valid UTF-8.",
1156
+ );
1157
+ }
1158
+ try {
1159
+ const deferredPasswordAuthorization = authorizationSourceConfigured();
1160
+ const resolveArguments = [
1161
+ "resolve",
1162
+ "--cwd",
1163
+ binding.safeCwd,
1164
+ "--workspace-root",
1165
+ HOST_WORKSPACE_ROOT,
1166
+ "--task-stdin",
1167
+ "--adapter-schema",
1168
+ ADAPTER_SCHEMA,
1169
+ ];
1170
+ if (deferredPasswordAuthorization) {
1171
+ resolveArguments.push("--defer-password-authorization");
1172
+ }
1173
+ if (selection !== undefined) {
1174
+ resolveArguments.push(
1175
+ "--select-attachment",
1176
+ selection.attachment_id,
1177
+ "--selection-task-digest",
1178
+ selection.task_digest,
1179
+ );
1180
+ if (selection.plan_digest !== undefined) {
1181
+ resolveArguments.push("--selection-plan-digest", selection.plan_digest);
1182
+ }
1183
+ resolveArguments.push("--selection-approved");
1184
+ }
1185
+ const resolution = validateResolution(
1186
+ runCliJson(resolveArguments, { input: taskInput }),
1187
+ {
1188
+ allowDeferredPasswordAuthorization: deferredPasswordAuthorization,
1189
+ },
1190
+ );
1191
+ resolvedWorkspaceRoot(binding, resolution);
1192
+ assertRecordBinding(binding);
1193
+ return {
1194
+ resolution,
1195
+ binding:
1196
+ resolution.decision === "load"
1197
+ ? bindSelectedAttachment(binding, resolution.selected)
1198
+ : binding,
1199
+ };
1200
+ } finally {
1201
+ taskInput.fill(0);
1202
+ }
1203
+ }
1204
+
1205
+ function resolveWorkspace(cwd, task, selection = undefined) {
1206
+ return resolveWorkspaceContext(cwd, task, selection).resolution;
1207
+ }
1208
+
1209
+ function workspaceStatus(cwd) {
1210
+ const binding = findWorkspaceBinding(cwd);
1211
+ const record = binding === null ? null : recordAtBinding(binding);
1212
+ return {
1213
+ document_type: "kdna.mcp.workspace-status",
1214
+ schema_version: ADAPTER_SCHEMA,
1215
+ attachments: record,
1216
+ };
1217
+ }
1218
+
1219
+ function adapterInfo() {
1220
+ return {
1221
+ name: packageInfo.name,
1222
+ version: packageInfo.version,
1223
+ cli: `${cliPackageInfo.name}@${CLI_VERSION}`,
1224
+ core: `@aikdna/kdna-core@${CORE_VERSION}`,
1225
+ };
1226
+ }
1227
+
1228
+ function adoptionControls(selected) {
1229
+ if (!selected) return null;
1230
+ return {
1231
+ view: "kdna attachments --cwd <workspace>",
1232
+ disable: `kdna disable ${selected.attachment_id} --cwd <workspace>`,
1233
+ switch: `kdna switch ${selected.attachment_id} <new-file.kdna> --cwd <workspace> --retain-scope --preview`,
1234
+ rollback: `kdna rollback ${selected.attachment_id} --cwd <workspace>`,
1235
+ };
1236
+ }
1237
+
1238
+ function judgmentDecisionSummary(runtimeCapsule) {
1239
+ const context = runtimeCapsule && runtimeCapsule.context;
1240
+ const axioms = context && Array.isArray(context.axioms) ? context.axioms : [];
1241
+ const decisionRules = [];
1242
+ for (const axiom of axioms) {
1243
+ if (!axiom || typeof axiom !== "object" || Array.isArray(axiom)) continue;
1244
+ const statement = axiom.statement || axiom.one_sentence || null;
1245
+ if (typeof statement !== "string" || statement.length === 0) continue;
1246
+ decisionRules.push({
1247
+ rule: statement,
1248
+ applies_when: Array.isArray(axiom.applies_when) ? axiom.applies_when : [],
1249
+ does_not_apply_when: Array.isArray(axiom.does_not_apply_when)
1250
+ ? axiom.does_not_apply_when
1251
+ : [],
1252
+ failure_risk: typeof axiom.failure_risk === "string" ? axiom.failure_risk : null,
1253
+ });
1254
+ }
1255
+ if (decisionRules.length === 0) return null;
1256
+ return {
1257
+ source: "runtime-capsule/context/axioms",
1258
+ rules: decisionRules,
1259
+ };
1260
+ }
1261
+
1262
+ function workspaceAdoption(resolution, scope = null, additions = {}) {
1263
+ return {
1264
+ document_type: "kdna.mcp.workspace-adoption",
1265
+ schema_version: ADAPTER_SCHEMA,
1266
+ adapter: adapterInfo(),
1267
+ adoption: resolution.decision,
1268
+ resolution,
1269
+ scope,
1270
+ controls: adoptionControls(resolution.selected),
1271
+ one_task_selection: additions.oneTaskSelection || null,
1272
+ host_processing: additions.hostProcessing || null,
1273
+ load_plan: additions.loadPlan || null,
1274
+ runtime_capsule: additions.runtimeCapsule || null,
1275
+ judgment_decision: additions.runtimeCapsule
1276
+ ? judgmentDecisionSummary(additions.runtimeCapsule)
1277
+ : null,
1278
+ };
1279
+ }
1280
+
1281
+ function workspaceProcessingBoundary(binding) {
1282
+ return {
1283
+ kind: "workspace_attachment",
1284
+ attachment_id: binding.selected.attachment_id,
1285
+ scope_digest: digestText(JSON.stringify(binding.scope)),
1286
+ };
1287
+ }
1288
+
1289
+ function loadWorkspace(args) {
1290
+ const { resolution, binding } = resolveWorkspaceContext(
1291
+ args.cwd,
1292
+ args.task,
1293
+ args.selection,
1294
+ );
1295
+ if (resolution.decision !== "load") return workspaceAdoption(resolution);
1296
+
1297
+ const authorizationBinding =
1298
+ resolution.authorization === "required" ? bindAuthorizationSource() : null;
1299
+ const processingBinding = hostProcessingConsent(
1300
+ resolution.selected.digest,
1301
+ args.profile,
1302
+ workspaceProcessingBoundary(binding),
1303
+ );
1304
+ assertWorkspaceBinding(binding);
1305
+ const loadPlan = runCliJson(["plan-load", binding.snapshot, "--json"], {
1306
+ acceptedStatuses: [0, 1, 3],
1307
+ });
1308
+ assertWorkspaceBinding(binding);
1309
+ const runtimeCapsule = loadRuntimeCapsule(
1310
+ binding.snapshot,
1311
+ args.profile,
1312
+ loadPlan,
1313
+ authorizationBinding,
1314
+ );
1315
+ assertWorkspaceBinding(binding);
1316
+ const confirmedProcessing = hostProcessingConsent(
1317
+ resolution.selected.digest,
1318
+ args.profile,
1319
+ workspaceProcessingBoundary(binding),
1320
+ );
1321
+ if (confirmedProcessing.consent_digest !== processingBinding.consent_digest) {
1322
+ throw new AdapterError(
1323
+ "host_processing_consent_invalid",
1324
+ "The Host processing consent is invalid or changed.",
1325
+ );
1326
+ }
1327
+ const satisfiedSelected = {
1328
+ ...resolution.selected,
1329
+ authorization: "satisfied",
1330
+ integrity: "verified",
1331
+ };
1332
+ const satisfiedResolution = {
1333
+ ...resolution,
1334
+ selected: satisfiedSelected,
1335
+ candidates: resolution.candidates.map((candidate) =>
1336
+ candidate.attachment_id === satisfiedSelected.attachment_id
1337
+ ? satisfiedSelected
1338
+ : candidate,
1339
+ ),
1340
+ authorization: "satisfied",
1341
+ };
1342
+ return workspaceAdoption(satisfiedResolution, binding.scope, {
1343
+ loadPlan,
1344
+ runtimeCapsule,
1345
+ hostProcessing: confirmedProcessing,
1346
+ oneTaskSelection:
1347
+ resolution.reason_code === "explicit_task_attachment_selection"
1348
+ ? {
1349
+ attachment_id: resolution.selected.attachment_id,
1350
+ task_digest: args.selection.task_digest,
1351
+ persisted: false,
1352
+ }
1353
+ : null,
1354
+ });
1355
+ }
1356
+
1357
+ async function callTool(name, args) {
1358
+ if (name === "kdna.workspace-status")
1359
+ return textResult(workspaceStatus(args.cwd));
1360
+ if (name === "kdna.workspace-resolve") {
1361
+ return textResult(resolveWorkspace(args.cwd, args.task, args.selection));
1362
+ }
1363
+ if (name === "kdna.workspace-load") return textResult(loadWorkspace(args));
1364
+ throw new AdapterError(
1365
+ "tool_unknown",
1366
+ "The requested KDNA tool is unavailable.",
1367
+ );
1368
+ }
1369
+
1370
+ async function handle({ id, method, params }) {
1371
+ if (method === "initialize") {
1372
+ sendResult(id, {
1373
+ protocolVersion: "2024-11-05",
241
1374
  capabilities: { tools: {} },
242
- serverInfo: { name: '@aikdna/kdna-mcp-server', version: packageInfo.version },
1375
+ serverInfo: { name: packageInfo.name, version: packageInfo.version },
243
1376
  });
244
1377
  return;
245
1378
  }
246
- if (method === 'tools/list') {
247
- send(id, { tools });
1379
+ if (method === "tools/list") {
1380
+ sendResult(id, { tools });
248
1381
  return;
249
1382
  }
250
- if (method === 'tools/call') {
251
- send(id, await callTool(params.name, params.arguments || {}));
1383
+ if (method === "tools/call") {
1384
+ let call;
1385
+ try {
1386
+ call = validatedToolCall(params);
1387
+ } catch (error) {
1388
+ if (error instanceof JsonRpcError) {
1389
+ sendError(id, error.code, error.message);
1390
+ return;
1391
+ }
1392
+ throw error;
1393
+ }
1394
+ try {
1395
+ sendResult(id, await callTool(call.name, call.args));
1396
+ } catch (error) {
1397
+ sendResult(id, toolErrorResult(error));
1398
+ }
252
1399
  return;
253
1400
  }
254
- if (id !== undefined) send(id, {});
1401
+ if (id !== undefined) sendError(id, -32601, "Method not found");
255
1402
  }
256
1403
 
257
1404
  const rl = readline.createInterface({ input: process.stdin });
258
- rl.on('line', async (line) => {
1405
+ rl.on("line", async (line) => {
259
1406
  if (!line.trim()) return;
260
1407
  let message;
261
1408
  try {
262
1409
  message = JSON.parse(line);
263
- await handle(message);
264
- } catch (e) {
265
- send(message?.id ?? null, null, e);
1410
+ } catch {
1411
+ sendError(null, -32700, "Parse error");
1412
+ return;
1413
+ }
1414
+
1415
+ let request;
1416
+ try {
1417
+ request = validatedJsonRpcMessage(message);
1418
+ } catch (error) {
1419
+ if (error instanceof JsonRpcError) {
1420
+ sendError(null, error.code, error.message);
1421
+ return;
1422
+ }
1423
+ sendError(null, -32603, "Internal error");
1424
+ return;
1425
+ }
1426
+
1427
+ if (request.isNotification) return;
1428
+ if (!request.paramsValid) {
1429
+ sendError(request.id, -32602, "Invalid params");
1430
+ return;
1431
+ }
1432
+ try {
1433
+ await handle(request);
1434
+ } catch {
1435
+ sendError(request.id, -32603, "Internal error");
266
1436
  }
267
1437
  });